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 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 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 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);
     }
 }
 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 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 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;
 }
 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');
 }
		 ('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)) {
            require_once PATH_CORE . '/classes/subscriptions.class.php';
            $subTable = new SubscriptionsTable($db);
 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 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;
 }
 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');
 }
 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');
         }
     }
 }
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";
        }
    }
}
 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 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 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 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...';
     */
 }
 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;
 }
 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;
 }
 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 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 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 debugNukeUser()
 {
     require_once PATH_CORE . '/classes/user.class.php';
     $userTable = new UserTable($this->db);
     $userInfoTable = new UserInfoTable($this->db);
     $user = $userTable->getRowObject();
     $userInfo = $userInfoTable->getRowObject();
     if ($user->load($this->page->session->userid)) {
         $user->delete();
         $code .= 'User entry deleted...';
     }
     if ($userInfo->load($this->page->session->userid)) {
         $userInfo->delete();
         $code .= 'UserInfo entry deleted...';
     }
     return $code;
 }