function ajaxUpdateHood($hood = '', $userid)
 {
     if ($hood != '') {
         // update userinfo table with chosen hood
         $uit = new UserInfoTable($this->db);
         $ui = $uit->getRowObject();
         $ui->load($userid);
         $ui->neighborhood = $hood;
         $ui->update();
         $hood = strtolower(preg_replace("/[^a-zA-Z]/", "", $hood));
         $this->templateObj->registerTemplates(MODULE_ACTIVE, 'newswire');
         if ($hood == 'all') {
             $q = "select id,title,caption,source,url,wireid\tfrom Newswire WHERE (select count(*) from Newswire as f WHERE f.feedid= Newswire.feedid and f.id > Newswire.id ) < 1 AND feedType='localBlog' ORDER BY id DESC LIMIT 7;";
         } else {
             $q = "SELECT id,title,caption,source,url,wireid FROM Newswire WHERE source IN (select title from Feeds WHERE FIND_IN_SET('" . $hood . "',tagList)) ORDER BY id DESC LIMIT 7;";
         }
         $this->templateObj->db->result = $this->templateObj->db->query($q);
         if ($this->templateObj->db->countQ($this->templateObj->db->result) > 0) {
             $this->templateObj->db->setTemplateCallback('safeTitle', array($this->utilObj, 'encodeCleanString'), array('title', 200));
             $this->templateObj->db->setTemplateCallback('safeCaption', array($this->utilObj, 'encodeCleanString'), array('caption', 500));
             $this->templateObj->db->setTemplateCallback('safeUrl', array($this->utilObj, 'encodeUrl'), 'url');
             $temp = $this->templateObj->mergeTemplate($this->templateObj->templates['sideWireList'], $this->templateObj->templates['sideWireItem']);
         } else {
             $temp = 'Could not find any stories.';
         }
     }
     $this->templateObj->resetCache('sideLocal_' . $userid);
     return $temp;
 }
 function process($data)
 {
     require_once PATH_CORE . '/classes/contactEmails.class.php';
     $cet = new ContactEmailTable($this->db);
     require_once PATH_CORE . '/classes/user.class.php';
     $userInfoTable = new UserInfoTable($this->db);
     $userInfo = $userInfoTable->getRowObject();
     $contactObj = $cet->getRowObject();
     $contactObj->email = $data['email'];
     $contactObj->subject = $data['subject'];
     $contactObj->message = $data['message'];
     $contactObj->userid = $data['userid'];
     $contactObj->date = date("Y-m-d H:i:s", time());
     $contactObj->topic = $data['topic'];
     $contactObj->insert();
     // Submit email to lighthouse app
     $userInfo->load($contactObj->userid);
     $lhemail = '*****@*****.**';
     $message = 'From: ' . $contactObj->email . "\n\n";
     $message .= 'User ID: ' . $contactObj->userid . "\n\n";
     $message .= 'Facebook profile: <a target="_blank" href="http://www.facebook.com/profile.php?id=' . $userInfo->fbId . '">http://www.facebook.com/profile.php?id=' . $userInfo->fbId . '</a>' . "\n\n";
     $message .= 'Subject: ' . $contactObj->subject . "\n\n";
     $message .= 'Topic: ' . $contactObj->topic . "\n\n";
     $message .= "\n\n\n\nMessage:\n\n" . $contactObj->message;
     mail($lhemail, $contactObj->subject, $message, 'From: support@newscloud.com' . "\r\n");
     $msg = 'Successfully submitted your comment. We will review this as soon as possible.';
     $this->page->app->facebook->redirect(URL_CANVAS . '?p=home&msgType=success&msgTitle=' . urlencode('Success!') . '&msg=' . urlencode($msg));
     //return '<p>Successfully submitted your comment. We will review this as soon as possible.</p>';
 }
 function userTest()
 {
     echo "\nDBTest User Test Page\n";
     require_once PATH_CORE . '/classes/user.class.php';
     $userTable = new UserTable($this->db);
     // TODO: cache instances of the tables globally
     $userInfoTable = new UserInfoTable($this->db);
     $user = $userTable->getRowObject();
     $userInfo = $userInfoTable->getRowObject();
     $isAppAuthorized = 0;
     $fbId = 666669;
     // create a test user
     $user->isAppAuthorized = $isAppAuthorized;
     if ($user->insert()) {
         // inserted ok
         echo '<p>created $user:<pre>' . print_r($user, true) . '</pre>';
         //$name = 'userid';
         //$user->{$name} = 1001;
         //$user->{'userid'} = 1001;
         echo "userid = {$user->userid}\n";
         if ($userInfo->createFromUser($user, $fbId)) {
             echo 'Created new user info\\n';
             echo "Primary keys should be equal: " . $user->userid . " ?= " . $userInfo->userid . ".\n";
             echo '<p>$userInfo:<pre>' . print_r($userInfo, true) . '</pre>';
             $userInfoTest = $userInfoTable->getRowObject();
             $userInfoTest->loadFromFbId($fbId);
             echo '<p>loaded user info debug: $userInfo:<pre>' . print_r($userInfoTest, true) . '</pre>';
             $userInfoTest->age = 111;
             $userInfoTest->update();
             $userInfoTest->loadFromFbId($fbId);
             echo '<p>updated user info debug: $userInfo:<pre>' . print_r($userInfoTest, true) . '</pre>';
             $user->name = "Roger Rabit";
             $user->update();
             // inserted ok
             echo '<p>updated $user:<pre>' . print_r($user, true) . '</pre>';
         } else {
             echo "Failed to create UserInfo row\n";
         }
     } else {
         echo "Failed to insert user!\n";
     }
     return $code;
 }
 function fetch($option = 'comments', $cid = 0)
 {
     // to do - remove, temp for vanishteam
     if (CACHE_PREFIX == 'van' and !$this->session->isAppAuthorized) {
         $fHandle = fopen(PATH_SERVER_LOGS . 'edr.log', 'a');
         fwrite($fHandle, 'Required to authorize:' . $_SERVER['HTTP_X_FB_USER_REMOTE_ADDR'] . "\n");
         $this->facebook = $this->session->app->loadFacebookLibrary();
         $user = $this->facebook->require_login();
     }
     // build the read story page
     require_once PATH_CORE . '/classes/read.class.php';
     $readObj = new read($this->db, $this->session);
     $readObj->setPageLink($this);
     require_once PATH_FACEBOOK . '/classes/actionTeam.class.php';
     $this->teamObj = new actionTeam($this->page);
     if (isset($_GET['cid']) and !is_numeric($_GET['cid'])) {
         $this->page->decloak();
     }
     if ($cid == 0) {
         // need for ajax readStory script
         if (isset($_GET['cid']) and is_numeric($_GET['cid'])) {
             $cid = $_GET['cid'];
         } else {
             exit('error2');
         }
     }
     $referid = $this->page->fetchReferral();
     if ($referid !== false && is_numeric($referid)) {
         // record chat action
         if (isset($_GET['chat'])) {
             if (!$this->session->isAppAuthorized) {
                 // require authorization so we can get their fbId - redirs to signup
                 $this->facebook = $this->session->app->loadFacebookLibrary();
                 $user = $this->facebook->require_login();
             }
             if (isset($_POST['fb_sig_added']) and $_POST['fb_sig_added'] == 1) {
                 $targetfbId = $_POST['fb_sig_user'];
             } else {
                 if (isset($_POST['fb_sig_canvas_user'])) {
                     $targetfbId = $_POST['fb_sig_canvas_user'];
                 } else {
                     $targetfbId = 0;
                 }
             }
             // make sure the referer is not clicking on the link themselves
             if ($targetfbId != 0 and $referid != $this->session->userid) {
                 // log referid as having referred this user
                 require_once PATH_CORE . '/classes/log.class.php';
                 $logObj = new log($this->db);
                 $logItem = $logObj->serialize(0, $referid, 'chatStory', $cid, $targetfbId);
                 $inLog = $logObj->update($logItem);
             }
         }
         // check for notification and display it
         if ($this->session->isLoaded and $referid != $this->session->userid) {
             // reader was referred here by someone
             require_once PATH_CORE . '/classes/notifications.class.php';
             $notificationsTable = new NotificationsTable($this->db);
             $msgid = $notificationsTable->lookupReferral($referid, $cid, $this->session->fbId);
             if ($msgid !== false and $msgid != '' and !is_null($msgid)) {
                 $notificationsTable->setStatus($msgid, $this->session->fbId, 'opened');
                 // get fbId from userid
                 require_once PATH_CORE . '/classes/user.class.php';
                 $uit = new UserInfoTable($this->db);
                 $ui = $uit->getRowObject();
                 $ui->load($referid);
                 $msgTable = new NotificationMessagesTable($this->db);
                 $msg = $msgTable->getRowObject();
                 // load the message
                 $msg->load($msgid);
                 // cast msg object into comment property array for token replacement
                 $referObj = array();
                 $referObj[fbId] = $ui->fbId;
                 $referObj[userid] = $referid;
                 $referObj[comments] = $msg->message;
                 $referObj[date] = $msg->dateCreated;
                 $referMsg = $readObj->fetchReferComment($referObj);
             }
         }
         $this->page->recordReferral($referid, 'referReader', $cid);
     }
     if (isset($_GET['viaBookmarklet'])) {
         //$inside.='<script type="text/javascript">function closeWindow() {window.opener = self;window.close();}</script><a href="#" onclick="closeWindow();">test</a>';
         //$inside.=$this->page->buildMessage('success','Your story has been posted','Click here if you wish to <a href="#" onclick="closeWindow();">close this window</a>.');
     } else {
         if (isset($_GET['justPosted'])) {
             // to do: put some options here
         }
     }
     $inside .= '<div id="col_left"><!-- begin left side -->';
     $inside .= $referMsg;
     $inside .= $readObj->fetchReadStory($cid, $option);
     $inside .= '</div><!-- end left side -->';
     $inside .= '<div id="col_right">';
     if ($this->session->isAdmin) {
         $inside .= '<div class="panel_1"><div class="panelBar clearfix">';
         $inside .= '<h2>Administrative Options</h2>';
         $inside .= '</div><!-- end panelBar -->';
         $inside .= '<div class="panel_block">';
         $inside .= '<ul><li><span id="banStoryPoster"><a href="#" onclick="banStoryPoster(' . $cid . ');return false;">Ban Member</a></span></li></ul>';
         // <span id="blockStory"><a href="#" onclick="blockStory('.$cid.');return false;">Block story</a></span><span class="pipe">|</span>
         $inside .= '</div><!-- end panel_block --></div><!-- end panel_1 -->';
     }
     $inside .= $readObj->fetchReadSidePanel($cid, $this->session, $this->page->isAjax);
     if (defined('ADS_ANY_SIDEBAR_BOTTOM')) {
         $inside .= str_replace("{ad}", '<fb:iframe src="' . URL_CALLBACK . '?p=cache&m=ad&locale=anySidebarBottom" frameborder="0" scrolling="no" style="width:180px;height:600px;padding:0px;margin:-5px 0px 0px 0px;"/>', $this->common['adWrapTallSidebar']);
     }
     $inside .= '</div> <!-- end right side -->';
     if ($this->page->isAjax) {
         return $inside;
     }
     $code .= '<input type="hidden" id="filter" value="default">';
     $code .= $this->page->constructPage('read', $inside);
     return $code;
 }
 function fetchProfileSummaryForProfileBox($fbId = 0, $canvasLink = URL_CANVAS)
 {
     $user = '';
     $userinfo = '';
     require_once PATH_CORE . '/classes/user.class.php';
     UserInfoTable::loadUserFromFbId($this->db, $fbId, &$user, &$userinfo);
     $code = '';
     // to do - strip this down to essential css
     //$code.='<style type="text/css">'.htmlentities(file_get_contents(PATH_FACEBOOK_STYLES.'/default.css', true)).'</style>';
     $css = htmlentities(file_get_contents(PATH_FACEBOOK_STYLES . '/default.css', true));
     $css = preg_replace('/\\s+-(moz|webkit).*/', '', $css);
     $css = str_replace('\\"', "'", $css);
     $code = '<style type="text/css">' . $css . '</style>';
     $code .= '<div id="profileBox">';
     $code .= '<div>';
     $code .= str_replace("{canvasLink}", $canvasLink, $this->commonTeam['ProfileBoxIntro']);
     if ($fbId != 0) {
         $this->setupLibraries();
         $code .= '<h2><fb:name uid="' . $fbId . '" capitalize="true" linked="true" useyou="false" /></h2>';
         $pointsRow = $this->profileSummaryRow("<span class=\"pointValue\">{$user->cachedPointTotal} <span class=\"pts\">points</span></span>\n\t\t\t&nbsp;" . ($showUserLevels ? $this->renderUserLevel($user->userLevel) : ''), '', '', true, true);
         $code .= '<div class="pointsTable_profile">
               <table cellspacing="0">
                 <tbody>
                 ' . $pointsRow . '        
                 </tbody>
               </table>
     			</div><!__end "pointsTable_profile"__>';
     }
     $code .= str_replace("{canvasLink}", $canvasLink, $this->commonTeam['ProfileBoxIntroJoinButton']);
     $code .= '</div><!--end "box"-->';
     //dev for rick
     if ($fbId == 756923320) {
         $code .= date("m-d H:i:s");
     }
     $code .= '</div><!--end profileBox-->';
     return $code;
 }
Exemplo n.º 6
0
         $sort = 'default';
     }
     require_once PATH_CORE . "/classes/prizes.class.php";
     $rwObj = new rewards();
     $code = $rwObj->fetchRewardsPage($sort, $currentPage, true, '', $session->u->eligibility);
     break;
 case 'fetchWinners':
     require_once PATH_CORE . "/classes/prizes.class.php";
     $rwObj = new rewards();
     $code = $rwObj->fetchWinners('', $currentPage);
     // hack: wont work w/ custom wherestring
     break;
 case 'hideTip':
     $tip = requestStr('tip');
     require_once PATH_CORE . '/classes/user.class.php';
     $userObj = new UserInfoTable($db);
     $userObj->hideTip($userid, $tip);
     $code = '';
     break;
 case 'log':
     $action = requestStr('action');
     $itemid = requestInt('itemid');
     require_once PATH_CORE . '/classes/log.class.php';
     $logObj = new log($db);
     $logItem = $logObj->serialize(0, $userid, $action, $itemid);
     $inLog = $logObj->update($logItem);
     break;
 case 'quickLog':
     $log = requestStr('log');
     $entry = new stdClass();
     $entry->action = requestStr('action');
 function buildCommentBox($isAjax = false)
 {
     $code = '';
     require_once PATH_CORE . '/classes/user.class.php';
     $userTable = new UserTable($this->db);
     $userInfoTable = new UserInfoTable($this->db);
     $user = $userTable->getRowObject();
     $userinfo = $userInfoTable->getRowObject();
     $user->loadWhere("isAdmin=1");
     $userinfo->load($user->userid);
     $code .= '<fb:comments xid="' . CACHE_PREFIX . '_microComments" canpost="true" candelete="true" simple="true" numposts="3" showform="true" publish_feed="false" quiet="true" send_notification_uid="' . $userinfo->fbId . '"></fb:comments>';
     // callbackurl="'.URL_CALLBACK.'?p=ajax&m=ideasRefreshComments&id='.$id.'"
     if (!$isAjax) {
         $code = '<div id="commentBox">' . $code . '</div>';
     }
     return $code;
 }
 function revokeAutomaticChallengeAward($userid, $shortname)
 {
     require_once PATH_CORE . '/classes/user.class.php';
     $challengeTable = new ChallengeTable($db);
     $userTable = new UserTable($db);
     $userInfoTable = new UserInfoTable($db);
     $completedTable = $this;
     $user = $userTable->getRowObject();
     $userInfo = $userInfoTable->getRowObject();
     $challenge = $challengeTable->getRowObject();
     $completed = $completedTable->getRowObject();
     $ccid;
     $res = $this->db->query("SELECT SQL_CALC_FOUND_ROWS ChallengesCompleted.id AS ccid \n\t\t\t\t\t\t\t\t\tFROM ChallengesCompleted,Challenges \n\t\t\t\t\t\t\t\t\t\tWHERE userid={$userid} \n\t\t\t\t\t\t\t\t\t\t\tAND Challenges.id = challengeid \n\t\t\t\t\t\t\t\t\t\t\tAND Challenges.shortName='{$shortname}'\n\t\t\t\t\t\t\t\t\t\t\tAND ChallengesCompleted.status='awarded';");
     if ($this->db->countQ($res)) {
         $data = $this->db->readQ($res);
     } else {
         return false;
     }
     $ccid = $data->ccid;
     if (!$completed->load($ccid)) {
         return false;
     }
     $completed->pointsAwarded = 0;
     $completed->dateAwarded = date('Y-m-d H:i:s', time());
     $completed->update();
     return true;
 }
 function updateSiteChallenges($limit = 1000)
 {
     $this->log('updateSiteChallenges...');
     $facebook = $this->getFacebookAPI();
     // check for profile box, sms, email optins
     // scan every use account and adjust the user level to match their cached points
     require_once PATH_CORE . '/classes/user.class.php';
     if ($limit == 0) {
         $useridList = $this->db->query("SELECT SQL_CALC_FOUND_ROWS\tuserid,fbId FROM UserInfo;");
         // $this->page->rowsPerPage
     } else {
         $useridList = $this->db->query("SELECT SQL_CALC_FOUND_ROWS\tuserid,fbId FROM UserInfo ORDER BY lastUpdateSiteChallenges ASC LIMIT 0,{$limit}");
         // $this->page->rowsPerPage
     }
     if ($this->db->countQ($useridList) == 0) {
         $this->log('updateSiteChallenges: got no user records!');
         return;
     }
     $userlist = array();
     while ($data = $this->db->readQ($useridList)) {
         $userlist[$data->fbId] = $data->userid;
     }
     //	$this->log("<pre>".print_r($userlist,true)."</pre>");
     $fqlquery = "SELECT email,sms,uid FROM permissions WHERE uid IN (" . implode(',', array_keys($userlist)) . ");";
     $this->log($fqlquery);
     try {
         $permissions_info = $facebook->api_client->fql_query($fqlquery);
     } catch (Exception $e) {
         $this->log($e->getMessage());
         $this->log($e->getTraceAsString());
         $this->log("updateSiteChallenges aborting safely");
     }
     //	$this->log("<pre>".print_r($permissions_info,true)."</pre>");
     $userTable = new UserTable($this->db);
     $user = $userTable->getRowObject();
     $userinfoTable = new UserInfoTable($this->db);
     $userinfo = $userinfoTable->getRowObject();
     if (is_array($permissions_info)) {
         foreach ($permissions_info as $permdata) {
             if ($user->load($userlist[$permdata['uid']])) {
                 // ask facebook whether they have -
                 //  - added to profile box? -- no way to detect this here :(
                 //  - authorized email
                 //  - authorized sms
                 //  - anything else we cant detect as it happens
                 /////////////////////////////////////////////////////
                 // email
                 $fbEmail = $permdata['email'];
                 $this->awardOrRevokeChallenge('optInEmail', $user->userid, $user->optInEmail, $fbEmail);
                 $user->optInEmail = $fbEmail;
                 // sms
                 $fbSMS = $permdata['sms'];
                 $this->awardOrRevokeChallenge('optInSMS', $user->userid, $user->optInSMS, $fbSMS);
                 $user->optInSMS = $fbSMS;
                 // more...?
                 /////////////////////////////////////////////////////
                 $user->lastUpdateSiteChallenges = date('Y-m-d H:i:s', time());
                 $user->update();
                 //$this->log('updated user '. $user->userid.'');
             } else {
                 $this->log('updateSiteChallenges: couldnt load user ' . $user->userid . '\\n');
             }
         }
     }
 }
function notifyUser($userid, $prizeid, $winEmailTemplate, $winNotTemplate)
{
    $claimURL = URL_CANVAS . "?p=redeem&id={$prizeid}";
    $claimLink = "<a href='" . $claimURL . "'>" . $claimURL . "</a>";
    $message .= "Prize {$prizeid} awarded to user {$userid}. ";
    $message .= "User needs to use following link to claim their prize: " . $claimLink;
    //////////////////////////
    // set up data to notify user
    require_once PATH_CORE . '/classes/user.class.php';
    $ut = new UserTable($db);
    $uit = new UserInfoTable($db);
    $user = $ut->getRowObject();
    $user->load($userid);
    require_once PATH_CORE . '/classes/prizes.class.php';
    $pt = new PrizeTable($db);
    $prize = $pt->getRowObject();
    $prize->load($prizeid);
    $nameWords = explode(" ", $user->name);
    require_once PATH_CORE . '/classes/template.class.php';
    $templateObj = new template($db);
    $columns['prizeTitle'] = $prize->title;
    $columns['claimURL'] = $claimURL;
    $columns['firstName'] = $nameWords[0];
    $callbacks = array();
    $winEmail = clone $winEmailTemplate;
    // i hate php
    $winNot = clone $winNotTemplate;
    // construct an email for this specific user
    $winEmail->email = $user->email;
    $winEmail->subject = $templateObj->processRow($columns, $winEmailTemplate->subject, $callbacks);
    $winEmail->body = $templateObj->processRow($columns, $winEmailTemplate->body, $callbacks);
    // construct notification info
    $winNot->body = $templateObj->processRow($columns, $winNotTemplate->body, $callbacks);
    $fbIds = $uit->getFbIdsForUsers(array($user->userid));
    $winNot->fbId = $fbIds[0];
    //$mailtoText = "mailto:$winEmail->email?subject=$winEmail->subject&body=$winEmail->body";
    // do send notifications
    echo "Mailing {$winEmail->email}...";
    sendEmail($winEmail);
    echo "Notifying {$winNot->fbId}...";
    sendNotification($winNot);
}
 function notifyOthers($comment, $story, &$app = NULL)
 {
     // sends notifications to users when people comment on a story they have posted or commented on
     if (MODULE_ACTIVE == 'FACEBOOK') {
         // comment is an array of the posted comment
         // story is an object of the story the comment is posted on
         require_once PATH_CORE . '/classes/user.class.php';
         $userInfoTable = new UserInfoTable($this->db);
         $ri = $userInfoTable->getRowObject();
         // recipient info
         $commentPoster = $comment['userid'];
         $commentPostedfbId = $comment['fbId'];
         $siteContentId = $comment['siteContentId'];
         $storyPoster = $story->userid;
         //$ignoreLink="http://www.newscloud.com/ver/igCom/{safeEmail}/{actCode}/".$commentid;
         $profileLink = '<a href="' . URL_CANVAS . '?p=account&o=subscribe">Change notifications?</a>';
         $storyLink = '<a href="' . URL_CANVAS . '?p=read&cid=' . $siteContentId . '&nc">' . $story->title . '</a>';
         // nc for no cache
         $app->loadFacebookLibrary();
         // check that commenter is not the poster
         if ($storyPoster != $commentPoster) {
             // notify poster of story
             // load the ui record for the fbId and if it succeeds, the corresponding user record
             if ($ri->load($storyPoster) and $ri->noCommentNotify == 0) {
                 // AND !$this->onIgnoreList($storyPoster,$commentPoster)
                 $msg = ' commented on your story, ' . $storyLink . ' at ' . SITE_TITLE . '. ' . $profileLink;
                 // $this->db->log($ri->fbId.' '.$msg);
                 // To ignore future comments by this reader, click the link below: '.$ignoreLink.'
                 // 	send notification
                 $apiResult = $app->facebook->api_client->notifications_send($ri->fbId, $msg, 'user_to_user');
             }
         }
         // notify other commenters
         // member name just added a comment, click here to view it
         $msg = ' replied to your comment from ' . $storyLink . ' at ' . SITE_TITLE . ' ' . $profileLink;
         $rxList = '';
         $listComments = $this->db->query("SELECT DISTINCT(userid) FROM Comments WHERE siteContentId={$siteContentId} AND userid<>{$storyPoster} AND userid<>{$commentPoster} LIMIT 99;");
         while ($data = $this->db->readQ($listComments)) {
             if ($ri->load($data->userid) and $ri->noCommentNotify == 0) {
                 // AND !$this->onIgnoreList($storyPoster,$commentPoster) {
                 $rxList .= $ri->fbId . ',';
             }
         }
         $rxList = trim($rxList, ',');
         if ($rxList != '') {
             // $this->db->log($rxList.' '.$msg);
             $apiResult = $app->facebook->api_client->notifications_send($rxList, $msg, 'user_to_user');
         }
     }
 }
 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 buildInvitePage()
 {
     // not tested since dropped into invite.class.php
     // REQUIRES Facebook session
     // some code taken from http://wiki.developers.facebook.com/index.php/Fb:request-forms
     /*echo "<pre>";			
     		echo '$this->facebook:'; print_r($this->facebook);
     		echo '$_GET:'; print_r( $_GET);
     		echo "</pre>";
     			*/
     require_once PATH_CORE . '/classes/user.class.php';
     $userid = $this->session->userid;
     $fbId = $this->session->fbId;
     if (isset($_GET['submit'])) {
         // Process posted invitation ids
         if (count($_POST['ids']) > 0) {
             $result = $this->templateObj->buildFacebookUserList('', $_POST['ids']);
             $result .= '<h1>Nice work!</h1><h5>What do you want to do now?</h5><div class="bullet_list"><ul>' . '<li><a href="?p=home" onclick="switchPage(\'home\');return false;">Go to the home page</a>?</li>' . '<li><a href="?p=team" onclick="switchPage(\'team\');return false;">Visit the ' . SITE_TEAM_TITLE . '</a>?</li>' . '</ul></div><!--end "bullet_list"-->';
             $code .= $this->page->buildMessage('success', 'Your invitations have been sent', $result);
             // Insert Invitations into table
             $inviteTable = new UserInviteTable($this->db);
             $invite = $inviteTable->getRowObject();
             $invite->userid = $userid;
             $invite->dateInvited = date('Y-m-d H:i:s', time());
             foreach ($_POST['ids'] as $id) {
                 $invite->friendFbId = $id;
                 $inviteid = UserInviteTable::checkExists($userid, $id);
                 if ($inviteid === false) {
                     $invite->insert();
                 } else {
                     $invite->id = $inviteid;
                     // date will be updated
                     $invite->update();
                 }
                 //$this->session->ui->cachedFriendsInvited++; // now done through log
                 $log = $this->page->app->getActivityLog();
                 $log->update($log->serialize(0, $this->session->userid, 'invite', $invite->friendFbId, 0));
                 // using itemid since userid2 implies the type is a userid, which it isnt
             }
             //$this->session->ui->update();
         } else {
             $code .= $this->page->buildMessage('error', 'Problem sending invitations', 'We encountered a problem sending your invitations. <a href="?p=invite" onclick="switchPage(\'invite\');return false;">Please try again</a>.');
         }
     } else {
         // Exclude users who have added the application already
         // TODO: do i use the fbApp action db for invitations?
         // Exclude users invited in the last 14 days by this user
         $userid = $this->session->userid;
         $inviteInterval = 3600 * 24 * 14;
         // 2 weeks in seconds
         $debug = false;
         $userInfoTable = new UserInfoTable($this->db);
         require_once PATH_CORE . '/classes/user.class.php';
         if ($debug) {
             echo 'session userinfo: <pre>' . print_r($this->session->ui, true) . '</pre>';
         }
         $allFriends = explode(',', $this->session->ui->friends);
         if ($debug) {
             echo 'session memberFriends: <pre>' . print_r($this->session->ui->memberFriends, true) . '</pre>';
         }
         $memberFriends = explode(',', $this->session->ui->memberFriends);
         // now cached
         if ($debug) {
             echo 'memberFriends uids: <pre>' . print_r($memberFriends, true) . '</pre>';
         }
         $memberFriends = $userInfoTable->getFbIdsForUsers($memberFriends);
         if ($debug) {
             echo 'memberFriends: <pre>' . print_r($memberFriends, true) . '</pre>';
         }
         //$invitedFriends = array();
         $invitedFriends = UserInviteTable::getRecentlyInvitedFriends($this->db, $userid, $inviteInterval);
         if ($debug) {
             echo 'invitedFriends: <pre>' . print_r($invitedFriends, true) . '</pre>';
         }
         if (is_null($invitedFriends)) {
             $invitedFriends = array();
         }
         if (is_null($memberFriends)) {
             $memberFriends = array();
         }
         $excludedFriends = array_merge($invitedFriends, $memberFriends);
         $excludedFriends = array_unique($excludedFriends);
         if ($debug) {
             echo 'excludedFriends: <pre>' . print_r($excludedFriends, true) . '</pre>';
         }
         $cntExcludedFriends = count($encludedFriends);
         //$allFriends=$this->facebook->api_client->friends_get();
         if (count($allFriends) <= $cntExcludedFriends) {
             //all friends are signed up or invited already
             $code .= '<h2>All your friends currently have the  ' . SITE_TITLE . ' application added or have been invited within the past two weeks.</h2><p>Thank you for supporting the ' . SITE_TITLE . '.</p>';
             $code .= '<p><a href="?p=home">Continue to home page</a></p>';
         } else {
             //  Construct a next url for referrals
             $nextUrl = $this->facebook->get_add_url("referfbid=" . $fbId . "&referid=" . $userid . "&viaInvite");
             //$this->db->log($nextUrl);
             $inviteText = $this->templateObj->templates['inviteText'] . "<fb:req-choice url=\"" . $nextUrl . "\" label=\"Add " . SITE_TITLE . "!\" />";
             // need to have this local jeff!
             $actionStr = $this->templateObj->templates['actionStr'];
             $code .= '<fb:request-form action="?p=invite&c=skipped&submit" method="POST" invite="true" type="' . SITE_TITLE . '" content="' . htmlentities($inviteText) . '">';
             if (is_numeric($this->page->app->notifications_per_day)) {
                 $maxRequests = $this->page->app->notifications_per_day;
             } else {
                 $maxRequests = 20;
             }
             $code .= '<fb:multi-friend-selector rows="5" max="' . $maxRequests . '" exclude_ids="' . join(',', $excludedFriends) . '" showborder="false"  actiontext="' . $actionStr . '"> </fb:request-form>';
         }
     }
     return $code;
 }
    function buildActionItem($action)
    {
        require_once PATH_CORE . '/classes/user.class.php';
        require_once PATH_CORE . '/classes/template.class.php';
        $uit = new UserInfoTable($this->db);
        $fbIds = $uit->getFbIdsForUsers(array($action->userid1));
        $fbId = $fbIds[0];
        if ($action->userid2) {
            $fbIds2 = $uit->getFbIdsForUsers(array($action->userid2));
            $fbId2 = $fbIds2[0];
        }
        if (!$fbId) {
            // cant return anything or #&*$@! paging gets screwed
            //$code .= '<div class="hidden">No fbId found for userid '. $action->userid1 . '</div>';
            $this->db->log("Action Feed: No fbId found for userid {$action->userid1} performing {$action->action} on {$action->t}");
            return '';
            //$code;
        }
        $ago .= self::getElapsedString(strtotime($action->t));
        switch ($action->action) {
            case 'completedChallenge':
                $code .= $this->fetchChallengeCompletedFeedItem($action, $fbId, false);
                // hack for now so the console can access it also
                //$ct = new ChallengeTable($this->db);
                break;
            case 'signup':
                /*$code .= template::buildLinkedProfilePic($fbIds[0], 'size="square"') .' '. template::buildLinkedProfileName($fbIds[0])
                				.' joined the action team!';
                		*/
                $code .= '<div class="profilePicLarger">' . template::buildLinkedProfilePic($fbIds[0], 'size="square"') . ' ' . '</div>
			                <div class="storyBlockWrap">
			                    <h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' joined the ' . SITE_TEAM_TITLE . '!</span> ' . $ago . '</h3>
			      		</div><!__end "storyBlockWrap"__>';
                break;
            case 'friendSignup':
                $code .= '<div class="profilePicLarger">' . template::buildLinkedProfilePic($fbIds[0], 'size="square"') . ' ' . '</div>
			                <div class="storyBlockWrap">
			                    <h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' got credit for inviting ' . template::buildLinkedProfileName($fbId2) . '!</span> ' . $ago . '</h3>
			      		</div><!__end "storyBlockWrap"__>';
                break;
            case 'chatStory':
                require_once PATH_CORE . '/classes/content.class.php';
                $contentTable = new ContentTable($this->db);
                $content = $contentTable->getRowObject();
                $contentid = $action->itemid;
                // hack: since jeff put the fbId in itemid2 for chatStory
                $fbId2 = $action->userid2;
                if ($content->load($contentid)) {
                    $code .= ' <div class="thumb">' . template::buildLinkedStoryImage($content->imageid, $contentid) . '</div>
				                <div class="storyBlockWrap">
				                	<div class="feed_poster">' . '<div class="avatar">' . template::buildLinkedProfilePic($fbIds[0], 'size="square"  with="30" height="30"') . '</div>' . '<div class="avatar">' . template::buildLinkedProfilePic($fbId2, 'size="square"  with="30" height="30"') . '</div>' . '<h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' chatted with ' . template::buildLinkedProfileName($fbId2) . ' about the story ' . template::buildStoryLink($content->title, $contentid) . '</span> ' . $ago . '</h3>
				                    </div>				                            
				                </div><!__end "storyBlockWrap"__>';
                }
                break;
                //case 'acceptedInvite': // actually want to filter these?
                // yeah, dont show these
                //break;
            //case 'acceptedInvite': // actually want to filter these?
            // yeah, dont show these
            //break;
            case 'redeemed':
                require_once PATH_CORE . '/classes/prizes.class.php';
                $prizeTable = new PrizeTable($this->db);
                $prize = $prizeTable->getRowObject();
                if ($prize->load($action->itemid) && !$prize->isWeekly && !$prize->isGrand) {
                    /*
                    $indefarticle = template::getIndefiniteArticle($prize->title);
                    $code .= template::buildLinkedProfilePic($fbIds[0], 'size="square"') .' '. template::buildLinkedProfileName($fbIds[0])
                    		." used {$prize->pointCost} points to get $indefarticle "
                    		. template::buildRewardLink($prize->title, $prize->id) .""
                    		. template::buildLinkedRewardPic($prize->id, $prize->thumbnail, $width=70);
                    //$code .= ' '. self::getElapsedString(strtotime($action->t));
                    */
                    $code .= '<div class="thumb">' . template::buildLinkedRewardPic($prize->id, $prize->thumbnail, $width = 70) . '</div>				           
				                <div class="storyBlockWrap">
				                	<div class="feed_poster"><div class="avatar">' . template::buildLinkedProfilePic($fbIds[0], 'size="square" with="30" height="30"') . '</div>
				                    	<h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' redeemed <span class="pointValue">' . $prize->pointCost . '<span class="pts"> points</span></span>.</span> ' . $ago . '</h3>
			                    	</div>
				                    <p class="storyHead">' . template::buildRewardLink($prize->title, $prize->id) . ' </p>
				                    <p class="storyCaption"></p>                
				                </div><!__end "storyBlockWrap"__>';
                } else {
                    // debug:
                    //$code .= 'No prize found for id ' . $action->itemid;
                }
                break;
            case 'wonPrize':
                // implement
                require_once PATH_CORE . '/classes/prizes.class.php';
                $prizeTable = new PrizeTable($this->db);
                $prize = $prizeTable->getRowObject();
                if ($prize->load($action->itemid)) {
                    if ($prize->isWeekly) {
                        $winText = 'won a Weekly Prize!';
                    }
                    if ($prize->isGrand == 1) {
                        $winText = 'won the Grand Prize and made the planet green with envy!';
                    }
                    if ($prize->isGrand > 1) {
                        $winText = 'won a Runner-up Prize!';
                    }
                    $code .= '<div class="thumb">' . template::buildLinkedRewardPic($prize->id, $prize->thumbnail, $width = 70) . '</div>
		                <div class="storyBlockWrap">
		                <div class="feed_poster"><div class="avatar">' . template::buildLinkedProfilePic($fbIds[0], 'size="square"  with="30" height="30"') . '</div>
		                    <h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' ' . $winText . ' ' . $ago . '</h3>
		                    </div>
		                    <p class="storyHead">' . template::buildRewardLink($prize->title, $prize->id) . ' </p>
		                    <p class="storyCaption"></p>                
		                </div><!__end "storyBlockWrap"__>';
                } else {
                    // debug:
                    //$code .= 'No prize found for id ' . $action->itemid;
                }
                break;
                break;
            case 'publishStory':
                // TODO ?
                //return '';
                //break;
            // TODO ?
            //return '';
            //break;
            case 'postBlog':
            case 'postStory':
                require_once PATH_CORE . '/classes/content.class.php';
                $contentTable = new ContentTable($this->db);
                $content = $contentTable->getRowObject();
                $contentid = $action->itemid;
                if ($content->load($contentid)) {
                    /*$code .= template::buildLinkedStoryImage($content->imageid, $contentid);
                    		$code .= template::buildLinkedProfilePic($fbIds[0], 'size="square"') .' '. template::buildLinkedProfileName($fbIds[0])
                    				.' posted a story';
                    		$code .= '<p>' . template::buildStoryLink($content->title, $contentid)
                    					.'</p>';
                    			*/
                    $code .= ' <div class="thumb">' . template::buildLinkedStoryImage($content->imageid, $contentid) . '</div>
				                <div class="storyBlockWrap">
				                	<div class="feed_poster"><div class="avatar">' . template::buildLinkedProfilePic($fbIds[0], 'size="square"  with="30" height="30"') . '</div>
				                    	<h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' posted a story</span> ' . $ago . '</h3>
				                    </div>
				                    <p class="storyHead">' . template::buildStoryLink($content->title, $contentid) . ' </p>
				                    <p class="storyCaption">' . $this->templateObj->ellipsis(strip_tags($content->caption, 200)) . ' ' . template::buildStoryLink('...more', $contentid) . '</p>                
				                </div><!__end "storyBlockWrap"__>';
                    //'</li>'
                }
                break;
            case 'vote':
                // ignore
                require_once PATH_CORE . '/classes/content.class.php';
                $contentTable = new ContentTable($this->db);
                $content = $contentTable->getRowObject();
                $contentid = $action->itemid;
                // grrrr
                if ($content->load($contentid)) {
                    $code .= ' <div class="thumb">' . template::buildLinkedStoryImage($content->imageid, $contentid) . '</div>
				                <div class="storyBlockWrap">
			                	<div class="feed_poster">' . '<h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' voted on the story ' . template::buildStoryLink($content->title, $contentid) . '</span> ' . $ago . '</h3>
				                    </div>
				                </div><!__end "storyBlockWrap"__>
				            ';
                }
                break;
            case 'comment':
                /*
                * 
                *  <li class="panel_block">
                                <div class="thumb"><a href="http://www.msnbc.msn.com/id/28529073/"><img src="{URL_BASE}/index.php?p=scaleImg&id=34608&x=185&y=130&fixed=x&crop" /></a>
                                </div>
                                <div class="storyBlockWrap">
                                    <h3><span class="bold"><a href="'.URL_CANVAS.'?p=profile&memberid=1180126201" onclick="return switchPage('profile', '', 1180126201);"><fb:name ifcantsee="Anonymous" uid="1180126201" capitalize="true" firstnameonly="false" linked="false" /></a> commented on the story <a href="#">It's Time to Aim Low</a></span> on Feb 2, 2009</h3>
                				<blockquote>
                					<div class="quotes">
                						<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor nunc, vehicula et, tristique sed, auctor et, massa.</p>
                						<p> Nam at purus vitae diam commodo venenatis. Ut leo enim, vestibulum eget, rhoncus in, suscipit laoreet, magna. Aliquam diam. Nunc tempor lorem eget nisl.</p>
                					</div>
                				</blockquote>
                                </div><!__end "storyBlockWrap"__>
                            </li>
                */
                // assume comment->siteContentId is what is stored...
                require_once PATH_CORE . '/classes/content.class.php';
                require_once PATH_CORE . '/classes/comments.class.php';
                require_once PATH_CORE . '/classes/video.class.php';
                $contentTable = new ContentTable($this->db);
                $commentTable = new CommentTable($this->db);
                $videoTable = new VideoTable($this->db);
                $content = $contentTable->getRowObject();
                $comment = $commentTable->getRowObject();
                $video = $videoTable->getRowObject();
                $commentid = $action->itemid;
                // grr
                $contentid = $action->itemid2;
                // grrrr
                if ($comment->load($commentid) && $content->load($contentid)) {
                    if ($comment->videoid && $video->load($comment->videoid)) {
                        $quoteContents = '<div style="text-align:center;">' . videos::buildPlayerFromLink($video->embedCode, 160, 100) . '</div>';
                    } else {
                        $quoteContents = '<p>' . $this->templateObj->ellipsis(strip_tags($comment->comments), 200) . ' ' . template::buildStoryLink('...more', $contentid) . '</p>';
                    }
                    $code .= ' <div class="thumb">' . template::buildLinkedStoryImage($content->imageid, $contentid) . '</div>
				                <div class="storyBlockWrap">
			                	<div class="feed_poster"><div class="avatar">' . template::buildLinkedProfilePic($fbIds[0], 'size="square" height="30" width="30"') . '</div>
				                    	<h3><span class="bold">' . template::buildLinkedProfileName($fbIds[0]) . ' commented on the story ' . template::buildStoryLink($content->title, $contentid) . '</span> ' . $ago . '</h3>
				                    </div>
				                    <blockquote>
				                    	<div class="quotes">' . $quoteContents . '</div>
									</blockquote>               
				                </div><!__end "storyBlockWrap"__>
				            ';
                }
                break;
        }
        return $code;
    }
 function processPrizeOrder($prizeid, $userid, &$message)
 {
     require_once PATH_CORE . '/classes/user.class.php';
     require_once PATH_CORE . '/classes/prizes.class.php';
     require_once PATH_CORE . '/classes/orders.class.php';
     $orderTable = new OrderTable($this->db);
     $userTable = new UserTable($this->db);
     $userInfoTable = new UserInfoTable($this->db);
     $prizeTable = new PrizeTable($this->db);
     $user = $userTable->getRowObject();
     $userInfo = $userInfoTable->getRowObject();
     $prize = $prizeTable->getRowObject();
     $order = $orderTable->getRowObject();
     if (!$user->load($userid) || !$userInfo->load($userid) || !$prize->load($prizeid)) {
         $message = "There was an error loading prize and/or user records.";
         return false;
     }
     $userInfoTable->updateUserCachedPointsAndChallenges($userid, $user, $userInfo);
     // slightly inefficient, calls load again
     // final check, in case something else happened
     if (!$this->checkOrderPossible($prize, $user, $userinfo, $message)) {
         return false;
     }
     // everythings ok:
     if (!($prize->isWeekly || $prize->isGrand)) {
         $user->cachedPointTotal -= $prize->pointCost;
     }
     $prize->currentStock--;
     $order->userid = $user->userid;
     $order->prizeid = $prize->id;
     $order->pointCost = $prize->pointCost;
     // cache points spent in here for proper recordkeeping.
     $phpnow = time();
     $order->dateSubmitted = date('Y-m-d H:i:s', $phpnow);
     $order->status = 'submitted';
     if (!$order->insert()) {
         $message = 'Error submitting your order, please email support.';
         return false;
     }
     $user->update();
     $prize->update();
     $message .= 'Your order number is #' . $order->id . '.';
     // debatable -- should this show up in the log if its a weekly or grand prize?
     $log = $this->app->getActivityLog();
     $log->add($log->serialize(0, $this->page->session->userid, 'redeemed', $_POST['prizeid'], 0));
     return $order->id;
 }
Exemplo n.º 16
0
 function ajaxAnswerNotifyOthers($mode = 'answer', $userid = 0, $id = 0, $qr = NULL, $answerid = 0)
 {
     // set up facebook framework library
     $facebook = $this->app->loadFacebookLibrary();
     // needed for api call below and requires setAppLink to be called before
     require_once PATH_CORE . '/classes/user.class.php';
     $userInfoTable = new UserInfoTable($this->db);
     $fbTx = '';
     $profileLink = '<a href="' . URL_CANVAS . '?p=account&o=subscribe">Change notifications?</a>';
     $qLink = '<a href="' . URL_CANVAS . '?p=ask&o=question&id=' . $id . '">' . htmlentities($qr->question) . '</a>';
     switch ($mode) {
         case 'answer':
             // answer - find question poster, answer posters and all comment posters - no dups
             // id is questionid
             // userid posted the answer
             // get list of people who answered this question
             $fbTx = $this->db->buildIdList("SELECT fbId AS id FROM AskAnswers LEFT JOIN UserInfo ON AskAnswers.userid=UserInfo.userid WHERE questionid={$id} ORDER BY id DESC LIMIT 25;");
             $msg = ' answered ' . $qLink . ' at ' . SITE_TITLE . '. ' . $profileLink;
             break;
         case 'comment':
             // send notification to person who posted original answer
             $answerPoster = $userInfoTable->getRowObject();
             // recipient info
             $answerPoster->load($userid);
             // fb:comments also notifies recent comment posters on the thread automatically
             $qLink = '<a href="' . URL_CANVAS . '?p=ask&o=question&id=' . $id . '&answerid=' . $answerid . '#aa_' . $answerid . '">' . htmlentities($qr->question) . '</a>';
             // nc for no cache
             // send this message to poster of the answer
             $msg = ' commented on your answer to ' . $qLink . ' at ' . SITE_TITLE . '. ' . $profileLink;
             $apiResult = $facebook->api_client->notifications_send($answerPoster->fbId, $msg, 'user_to_user');
             // send different msg to question poster
             $msg = ' commented on an answer to ' . $qLink . ' at ' . SITE_TITLE . '. ' . $profileLink;
             // pass thru - below will send notify to user who posted question
             break;
     }
     // get fbId of original question poster
     // to do - only send to question poster if qr->fbId <> fb:comment poster fbId
     $ri = $userInfoTable->getRowObject();
     // recipient info
     $ri->load($qr->userid);
     if ($fbTx != '') {
         $fbTx .= ',';
     }
     $fbTx .= $ri->fbId;
     // send notifications
     $apiResult = $facebook->api_client->notifications_send($fbTx, $msg, 'user_to_user');
 }
$action = new stdClass;
$action->action= 'completedChallenge';
$action->itemid = $completed_challenge['id'];
$userid = $completed_challenge['userid'];
$action->userid1 = $userid;
// could fill in fbId here if we werent lazy too
$fbId = 0; 

$actionFeed = new actionFeed();
$report = $actionFeed->fetchChallengeCompletedFeedItem( $action , $fbId, true); 
echo $report;
*/
///////////////////////////
// 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)) {
 function ajaxBanStoryPoster(&$app = null, $cid = 0, $userid = 0)
 {
     // to do - make sure user is admin
     // cid - cid of user to ban
     $contentTable = new ContentTable($this->db);
     $c = $contentTable->getRowObject();
     $c->load($cid);
     if ($c->userid != $userid) {
         $this->db->update("Content", "isBlocked=1", "userid=" . $c->userid);
         // block all stories by this user
         $this->db->update("Comments", "isBlocked=1", "userid=" . $c->userid);
         // block all comments by this user
         require_once PATH_CORE . '/classes/user.class.php';
         $uit = new UserInfoTable($this->db);
         $ut = new UserTable($this->db);
         $u = $ut->getRowObject();
         $ui = $uit->getRowObject();
         $u->load($c->userid);
         // block story
         $c->isBlocked = 1;
         $c->update();
         // block user
         $u->isBlocked = 1;
         $u->update();
         $ui->load($c->userid);
         $facebook = $app->loadFacebookLibrary();
         $this->db->log('To Ban ' . $ui->fbId);
         //$facebook->api_client->admin_banUsers($ui->fbId);
         // load facebook library - call ban api
         $code = 'Ban complete.';
     } else {
         $code = 'Error: Trying to ban yourself again, huh?';
     }
     return $code;
 }
 function updateUserCachedPoints($fbId, $always = false)
 {
     require_once PATH_CORE . '/classes/user.class.php';
     $userTable = new UserTable($this->db);
     $user = $userTable->getRowObject();
     $userinfoTable = new UserInfoTable($this->db);
     $userinfo = $userinfoTable->getRowObject();
     if ($userinfo->loadWhere("fbId={$fbId} " . ($always ? "" : "AND DATE_ADD(lastUpdateCachedPointsAndChallenges, INTERVAL 1 HOUR) < NOW()"))) {
         $userinfoTable->updateUserCachedPointsAndChallenges($userinfo->userid, &$user, &$userinfo, $weekOf);
     }
 }
Exemplo n.º 20
0
function initializeUserInfo($fbId = 0)
{
    global $db;
    // adds a record for this user in the Facebook app userinfo table
    require_once PATH_CORE . '/classes/user.class.php';
    $userTable = new UserTable($db);
    // TODO: cache instances of the tables globally
    $userInfoTable = new UserInfoTable($db);
    $user = $userTable->getRowObject();
    $userInfo = $userInfoTable->getRowObject();
    //dbRowObject::$debug = true;
    $debug = true;
    if ($debug) {
        echo 'entered postAuth::initializeUserInfo()\\n';
    }
    // create new users
    $user->isAppAuthorized = 1;
    $user->votePower = 1;
    if ($user->insert()) {
        // inserted ok
        if ($debug) {
            echo '<p>created $user:<pre>' . print_r($user, true) . '</pre>';
        }
        if ($userInfo->createFromUser($user, $fbId)) {
            //*
            if ($debug) {
                echo 'Created new user info\\n';
                echo '<p>$userInfo:<pre>' . print_r($userInfo, true) . '</pre>';
            }
            //*/
            $userInfoTest = $userInfoTable->getRowObject();
            $userInfoTest->loadFromFbId($fbId);
            // populate subscription settings for the new user
            require_once PATH_CORE . '/classes/subscriptions.class.php';
            $subTable = new SubscriptionsTable($db);
            $sub = $subTable->getRowObject();
            $sub->userid = $user->userid;
            $sub->rxFeatures = 1;
            $sub->rxMode = 'notification';
            $sub->insert();
            if ($debug) {
                echo '<p>fetched user info debug: $userInfo:<pre>' . print_r($userInfoTest, true) . '</pre>';
            }
        } else {
            if ($debug) {
                echo "Failed to create UserInfo row:<br>";
                echo '<p>$userInfo:<pre>' . print_r($userInfo, true) . '</pre>';
            }
        }
    } else {
        if ($debug) {
            echo "Failed to insert user!\n";
        }
    }
}
Exemplo n.º 21
0
 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;
         }
     }
 }
 // to do - move this to a dbrowobject model - and replace in facebook initdb too
 $manageObj->addTable("SystemStatus", "id", "INT(4) unsigned NOT NULL auto_increment", "MyISAM");
 $manageObj->addColumn("SystemStatus", "name", "VARCHAR(35) default ''");
 $manageObj->addColumn("SystemStatus", "strValue", "TEXT default ''");
 $manageObj->addColumn("SystemStatus", "numValue", "BIGINT(20) default 0");
 //////////////////////////////////////////////////////////////////////////////////////////
 // news-specific tables
 if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'dynamicTemplate.class.php')) {
     require_once PATH_CORE . '/classes/dynamicTemplate.class.php';
     TemplateTable::createTable($manageObj);
 }
 if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'user.class.php')) {
     // Create the User table
     require_once PATH_CORE . '/classes/user.class.php';
     UserTable::createTable($manageObj);
     UserInfoTable::createTable($manageObj);
     $userInfoTable = new UserInfoTable($manageObj->db);
     UserInviteTable::createTable($manageObj);
 }
 // set up newswire table
 $manageObj->addTable("Newswire", "id", "INT(11) unsigned NOT NULL auto_increment", "MyISAM");
 $manageObj->addColumn("Newswire", "title", "VARCHAR(255) default ''");
 $manageObj->addColumn("Newswire", "caption", "TEXT default ''");
 $manageObj->addColumn("Newswire", "source", "VARCHAR (150) default ''");
 $manageObj->addColumn("Newswire", "url", "VARCHAR(255) default ''");
 $manageObj->addColumn("Newswire", "date", "DATETIME");
 // to do - deprecate
 $manageObj->addColumn("Newswire", "wireid", "INT(11) default 0");
 // deprecated
 $manageObj->addColumn("Newswire", "feedid", "INT(11) default 0");
 if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'content.class.php')) {
 function initializeUserInfo($fbId = 0, $isAppAuthorized = 0)
 {
     // adds a record for this user in the Facebook app userinfo table
     require_once PATH_CORE . '/classes/user.class.php';
     $userTable = new UserTable($this->db);
     // TODO: cache instances of the tables globally
     $userInfoTable = new UserInfoTable($this->db);
     $user = $userTable->getRowObject();
     $userInfo = $userInfoTable->getRowObject();
     //dbRowObject::$debug = true;
     $debug = false;
     if ($debug) {
         echo 'entered session::initializeUserInfo()\\n';
     }
     // create new users
     $user->isAppAuthorized = $isAppAuthorized;
     $user->votePower = 1;
     if ($user->insert()) {
         // inserted ok
         if ($debug) {
             echo '<p>created $user:<pre>' . print_r($user, true) . '</pre>';
         }
         if ($userInfo->createFromUser($user, $fbId)) {
             //*
             if ($debug) {
                 echo 'Created new user info\\n';
                 echo '<p>$userInfo:<pre>' . print_r($userInfo, true) . '</pre>';
             }
             //*/
             $userInfoTest = $userInfoTable->getRowObject();
             $userInfoTest->loadFromFbId($fbId);
             if ($debug) {
                 echo '<p>fetched user info debug: $userInfo:<pre>' . print_r($userInfoTest, true) . '</pre>';
             }
             // populate subscription settings for the new user
             require_once PATH_CORE . '/classes/subscriptions.class.php';
             $subTable = new SubscriptionsTable($this->db);
             $sub = $subTable->getRowObject();
             $sub->userid = $user->userid;
             $sub->rxFeatures = 1;
             $sub->rxMode = 'notification';
             $sub->insert();
         } else {
             if ($debug) {
                 echo "Failed to create UserInfo row:<br>";
                 echo '<p>$userInfo:<pre>' . print_r($userInfo, true) . '</pre>';
             }
             return false;
         }
     } else {
         if ($debug) {
             echo "Failed to insert user!\n";
         }
         return false;
     }
     // merge necessary session data into a results object and return it
     $data->isMember = $user->isMember;
     $data->isBlocked = $user->isBlocked;
     $data->isAdmin = $user->isAdmin;
     $data->name = $userInfo->name;
     $data->userid = $userInfo->userid;
     // .. etc
     return $data;
     /*   
     	echo "<p>session->fbId: {$this->app->session->fbId}</p>";
     	$userInfo->loadFromFbId($this->app->session->fbId);
     	
     	echo '<p>$userInfo:<pre>'. print_r($userInfo).'</pre>';
     	
     	if ($userInfo->userid && $user->load($userInfo->userid))
     		{
     		$code .= 'Found a user...';
     */
 }
 static function getMemberFriends($db, $userid)
 {
     if (is_null($db)) {
         require_once PATH_CORE . '/classes/db.class.php';
         $db = new cloudDatabase();
     }
     require_once PATH_CORE . '/classes/user.class.php';
     $userInfoTable = new UserInfoTable($db);
     $userinfo = $userInfoTable->getRowObject();
     if ($userinfo->load($userid)) {
         return $userInfoTable->getFbIdsForUsers(explode(',', $userinfo->memberFriends));
     }
     return null;
 }
		$db->insert("SystemStatus","name,strValue,numValue","'fbApp_',null,0");
		 ('22','fbApp_info_changed_url','',null),
		 ('25','fbApp_edit_url','',null),
		 ('27','fbApp_desktop',null,'0'),
		 ('13','fbApp_private_install',null,'0'),
		 ('30','fbApp_default_column',null,'1'),
		 ('34','fbApp_base_domain','',null),
		*/
// Add admin user
$q = $db->query("SELECT * FROM User WHERE isAdmin=1");
if ($db->countQ($q) == 0) {
    echo 'Adding ' . SUPPORT_ADMIN . ' as administrator...<br />';
    require_once PATH_CORE . '/classes/user.class.php';
    $userTable = new UserTable($db);
    // TODO: cache instances of the tables globally
    $userInfoTable = new UserInfoTable($db);
    $user = $userTable->getRowObject();
    $userInfo = $userInfoTable->getRowObject();
    // create new users
    $user->name = SITE_TITLE . ' Administrator';
    $user->isAppAuthorized = 1;
    $user->votePower = 1;
    $user->isAdmin = 1;
    $user->authLevel = 'member';
    $user->eligibility = 'team';
    $user->email = SUPPORT_ADMIN;
    $user->ncUid = rand(0, 99999);
    // deprecated column, but must be set
    if ($user->insert()) {
        // inserted ok
        if ($userInfo->createFromUser($user, 0)) {
    function fetchNetworks()
    {
        // get location, networks and groups
        if ($this->session->isLoaded) {
            if (is_null($this->session->ui->lastNetSync) or time() - strtotime($userinfo->lastNetSync) > 7 * 24 * 60 * 60) {
                $queries = '{
				  "networks":"SELECT affiliations, current_location FROM user WHERE uid=' . $this->session->fbId . '",
					"groups":"SELECT gid,name FROM group WHERE gid IN (SELECT gid FROM group_member WHERE uid =' . $this->session->fbId . ')"
				}';
                $this->facebook = $this->session->app->loadFacebookLibrary();
                try {
                    $resp = $this->facebook->api_client->fql_multiquery($queries);
                    $r = $this->parseMulitquery($resp);
                    require_once PATH_CORE . '/classes/user.class.php';
                    $userInfoTable = new UserInfoTable($this->db);
                    $userinfo = $userInfoTable->getRowObject();
                    if ($userinfo->loadFromFbId($this->session->fbId)) {
                        $userinfo->updateNetworks($r);
                    }
                    $this->session->ui->groups = $userinfo->groups;
                    $this->session->ui->networks = $userinfo->networks;
                } catch (Exception $e) {
                    $this->db->log($e);
                }
            }
        }
    }
 function ajaxNotifyOthers($userid = 0, $id = 0, $ir = NULL)
 {
     // set up facebook framework library
     $facebook = $this->app->loadFacebookLibrary();
     // needed for api call below and requires setAppLink to be called before
     $profileLink = '<a href="' . URL_CANVAS . '?p=account&o=subscribe">Change notifications?</a>';
     $qLink = '<a href="' . URL_CANVAS . '?p=ideas&o=view&id=' . $id . '">' . htmlentities($ir->idea) . '</a>';
     $msg = ' commented on your idea ' . $qLink . ' at ' . SITE_TITLE . '. ' . $profileLink;
     require_once PATH_CORE . '/classes/user.class.php';
     $userInfoTable = new UserInfoTable($this->db);
     $ideaPoster = $userInfoTable->getRowObject();
     // recipient info
     // send notification to person who posted original idea
     $ideaPoster->load($userid);
     // fb:comments also notifies recent comment posters on the thread automatically
     $apiResult = $facebook->api_client->notifications_send($ideaPoster->fbId, $msg, 'user_to_user');
 }
Exemplo n.º 28
0
 function userAcceptedInvitation($userid)
 {
     //$userTable = new UserTable($this->db);
     //$user = $userTable->getRowObject();
     $userInfoTable = new UserInfoTable($this->db);
     $userInfo = $userInfoTable->getRowObject();
     $userinvite = $this->getRowObject();
     //($user->load($userid) &&
     if (!$userInfo->load($userid)) {
         return false;
     }
     //$this->db->setDebug(true); // NEVER TURN ON FOR LIVE SITE
     if ($userinvite->loadFromFbIdAndUserid($userInfo->fbId, $userInfo->refuid)) {
         $userinvite->dateAccepted = date('Y-m-d H:i:s', time());
         $userinvite->update();
         return true;
     } else {
         // echo '<p>Couldnt find an invitation to accept!</p>';
     }
     return false;
 }
 function fetchReferral()
 {
     // lookds for referid userid or referfbid facebook id
     // returns userid
     if (isset($_GET['referid'])) {
         $referid = $_GET['referid'];
     } else {
         if (isset($_GET['referfbid'])) {
             $referfbid = $_GET['referfbid'];
             // look up userid from facebook id
             require_once PATH_CORE . '/classes/user.class.php';
             $userInfoTable = new UserInfoTable($this->db);
             $userinfo = $userInfoTable->getRowObject();
             if ($userinfo->loadFromFbId($referfbid) !== false) {
                 if ($referid != $userinfo->userid) {
                     // prevent referid from getting set to self in bizzare cases
                     $referid = $userinfo->userid;
                 }
             } else {
                 return false;
             }
         } else {
             return false;
         }
     }
     return $referid;
 }
 function initFormDataFromDatabase($userid)
 {
     $fdata = new stdClass();
     require_once PATH_CORE . '/classes/user.class.php';
     $userTable = new UserTable($this->db);
     $userInfoTable = new UserInfoTable($this->db);
     $user = $userTable->getRowObject();
     $userinfo = $userInfoTable->getRowObject();
     //dbRowObject::$debug = 1;
     if (!$user->load($this->session->userid) || !$userinfo->load($this->session->userid)) {
         $fdata->alert = 'Fatal error: userid not found in database';
         $fdata->result = false;
         echo 'Error loading user table entries.';
         return $fdata;
     }
     $fdata->age = $userinfo->age;
     $fdata->city = $userinfo->city;
     $fdata->state = $userinfo->state;
     $fdata->country = $userinfo->country;
     $fdata->address1 = $userinfo->address1;
     $fdata->address2 = $userinfo->address2;
     $fdata->zip = $userinfo->zip;
     $fdata->gender = $userinfo->gender;
     //$userinfo->birthdate = ''; // TODO
     $fdata->name = $user->name;
     $fdata->email = $user->email;
     $fdata->optInStudy = $user->optInStudy;
     $fdata->optInEmail = $user->optInEmail;
     $fdata->optInSMS = $user->optInSMS;
     $fdata->optInProfile = $user->optInProfile;
     $fdata->optInFeed = $user->optInFeed;
     $fdata->noCommentNotify = $userinfo->noCommentNotify;
     $fdata->acceptRules = $user->acceptRules;
     require_once PATH_CORE . '/classes/subscriptions.class.php';
     $subTable = new SubscriptionsTable($this->db);
     $sub = $subTable->getRowObject();
     if ($sub->loadWhere("userid=" . $this->session->userid)) {
         $fdata->rxFeatures = $sub->rxFeatures;
         $fdata->rxMode = $sub->rxMode;
     } else {
         $fdata->rxFeatures = 1;
         $fdata->rxMode = 'notification';
     }
     return $fdata;
 }