protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $url = sfConfig::get('op_base_url');
     if ($arguments['mode'] == "morning") {
         $message = "おはようございます。昨日の勤怠報告が済んでいない方は報告よろしくお願いします。";
     } elseif ($arguments['mode'] == "afternoon") {
         $message = "お疲れ様です。退勤される方は勤怠報告をよろしくおねがいします。";
     } elseif ($arguments['mode'] == "evening") {
         $message = "お疲れ様です。退勤される方は勤怠報告をよろしくおねがいします。";
     } else {
         $message = "";
     }
     if ($message) {
         $message = $message . " " . $url . "/kintai";
         $activity = new ActivityData();
         $activity->setMemberId(1);
         $activity->setBody($message);
         $activity->setIsMobile(0);
         $activity->save();
         echo "Posted via Acvitity.\n";
     } else {
         echo "Posted failure. Maybe incorrect arguments.\n";
     }
 }
 public function updateTimeline($request)
 {
     $newObject = new ActivityData();
     $newObject->setMemberId($this->getUser()->getMemberId());
     $this->form = new TimelineDataForm($newObject);
     $params = $request->getParameter('activity_data');
     $this->form->bind($params);
     if ($this->form->isValid()) {
         $this->form->save();
         if ($request->isXmlHttpRequest()) {
             $this->getContext()->getConfiguration()->loadHelpers('Partial');
             return $this->renderText(get_partial('default/activityRecord', array('activity' => $this->form->getObject())));
         } else {
             $this->redirect($params['next_uri']);
         }
     } else {
         if ($request->isXmlHttpRequest()) {
             $this->getResponse()->setStatusCode(500);
         } else {
             $this->getUser()->setFlash('error', 'Failed to post %activity%.');
             if (isset($params['next_uri'])) {
                 $this->redirect($params['next_uri']);
             }
             $this->redirect('@homepage');
         }
     }
 }
Beispiel #3
0
 /**
  * Activity::frontpage()
  * 
  * @param integer $count
  * @return void
  */
 public function frontpage($count = 20)
 {
     $activities = ActivityData::getActivity(array(), $count);
     if (!$activities) {
         $activities = array();
     }
     $this->set('allactivities', $activities);
     $this->render('activity_list.tpl');
 }
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
    $this->conn = $databaseManager->getDatabase('doctrine')->getDoctrineConnection();

    $sql = 'SELECT id FROM member WHERE is_active != 0';
    $where = array();
    if ( $options['min'] && $options['max']  && $options['min'] <= $options['max'])
    {
        $sql .= ' AND id BETWEEN ? AND ?';
        $where = array(intval($options['min']),intval($options['max']));
    }
    $memberIds = $this->conn->fetchColumn($sql, $where);

    foreach ($memberIds as $memberid)
    {
      for ($i=0; $i<$options['number']; ++$i)
      {
        $ac = new ActivityData();
        $ac->setMemberId($memberid);
        $ac->setBody(md5($i));
        $ac->setPublicFlag(1);
        $ac->save();
        $ac->free();
        $this->logSection('posted a activity', sprintf('%s', $memberid));
      }
    }
  }
 public static function activityToStatus(ActivityData $activity, $isTermUser = false)
 {
     $result = array('created_at' => $activity->getCreatedAt(), 'id' => $activity->getId(), 'text' => $activity->getBody());
     if ($isTermUser) {
         $result['user'] = array('id' => $activity->getMemberId());
     } else {
         $result['user'] = self::memberToUser($activity->getMember());
     }
     return $result;
 }
Beispiel #6
0
function post_module_load()
{
    /* Misc tasks which need to get done */
    /* If the setting to auto-retired pilots is on, then do that
       and only check every 24 hours
       */
    if (Config::Get('USE_CRON') == false) {
        if (Config::Get('PILOT_AUTO_RETIRE') == true) {
            $within_timelimit = CronData::check_hoursdiff('find_retired_pilots', '24');
            if ($within_timelimit === false) {
                PilotData::findRetiredPilots();
                CronData::set_lastupdate('find_retired_pilots');
            }
        }
        if (Config::Get('CLOSE_BIDS_AFTER_EXPIRE') === false) {
            $within_timelimit = CronData::check_hoursdiff('check_expired_bids', '24');
            if ($within_timelimit === false) {
                SchedulesData::deleteExpiredBids();
                CronData::set_lastupdate('check_expired_bids');
            }
        }
        /* Expenses, make sure they're all populated */
        $within_timelimit = CronData::check_hoursdiff('populate_expenses', 18);
        if ($within_timelimit === false) {
            FinanceData::updateAllExpenses();
            CronData::set_lastupdate('populate_expenses');
        }
        /* And finally, clear expired sessions */
        Auth::clearExpiredSessions();
    }
    if (Config::Get('TWITTER_AIRLINE_ACCOUNT') != '') {
        $within_timelimit = CronData::check_hoursdiff('twitter_update', '3');
        if ($within_timelimit === false) {
            ActivityData::readTwitter();
            CronData::set_lastupdate('twitter_update');
        }
    }
    // @TODO: Clean ACARS records older than one month
    if (Config::Get('MAINTENANCE_MODE') == true && !Auth::LoggedIn() && !PilotGroups::group_has_perm(Auth::$usergroups, FULL_ADMIN)) {
        Template::Show('maintenance.tpl');
        die;
    }
    return true;
}
 public function updateActivity($memberId, $body, $options = array())
 {
     $object = new ActivityData();
     $object->setMemberId($memberId);
     $object->setBody($body);
     if (isset($options['template'])) {
         $object->setTemplate($options['template']);
         if (isset($options['template_param']) && is_array($options['template_param'])) {
             $object->setTemplateParam($options['template_param']);
         }
     }
     if (isset($options['public_flag'])) {
         $publicFlagKeys = array_keys($this->getPublicFlags(false));
         if (!in_array($options['public_flag'], $publicFlagKeys)) {
             throw new LogicException('Invalid public flag');
         }
         $object->setPublicFlag($options['public_flag']);
     }
     if (isset($options['in_reply_to_activity_id'])) {
         $object->setInReplyToActivityId($options['in_reply_to_activity_id']);
     }
     if (isset($options['is_pc']) && !$options['is_pc']) {
         $object->setIsPc(false);
     }
     if (isset($options['is_mobile']) && !$options['is_mobile']) {
         $object->setIsMobile(false);
     }
     if (isset($options['uri'])) {
         $object->setUri($options['uri']);
     }
     if (isset($options['source'])) {
         $object->setSource($options['source']);
         if (isset($options['source_uri'])) {
             $object->setSourceUri($options['source_uri']);
         }
     }
     $activityImages = array();
     if (isset($options['images'])) {
         if (!is_array($options['images'])) {
             $options['images'] = array($options['images']);
         }
         foreach ($options['images'] as $image) {
             $activityImage = new ActivityImage();
             if (isset($image['file_id'])) {
                 $file = Doctrine_Core::getTable('File')->find($image['file_id']);
                 if (!$file) {
                     throw new LogicException('Invalid file_id.');
                 }
                 $activityImage->setFileId($file->getId());
                 $activityImage->setMimeType($file->getType());
             } elseif (isset($image['uri']) && isset($image['mime_type'])) {
                 $activityImage->setUri($image['uri']);
                 $activityImage->setMimeType($image['mime_type']);
             } else {
                 throw new LogicException('Invalid image data');
             }
             $activityImages[] = $activityImage;
         }
     }
     if (isset($options['foreign_table']) && isset($options['foreign_id'])) {
         $object->setForeignTable($options['foreign_table']);
         $object->setForeignId($options['foreign_id']);
     }
     $object->save();
     foreach ($activityImages as $activityImage) {
         $activityImage->setActivityData($object);
         $activityImage->save();
     }
     return $object;
 }
 public function executeShowAllMemberActivity(opWebRequest $request)
 {
     if (!isset($this->size)) {
         $this->size = 20;
     }
     $page = $request->getParameter('page', 1);
     if ($page == 1 && opConfig::get('is_allow_post_activity')) {
         $activityData = new ActivityData();
         $activityData->setBody($request->getParameter('body'));
         $this->form = new ActivityDataForm($activityData);
     }
     $this->pager = Doctrine::getTable('ActivityData')->getAllMemberActivityListPager($page, $this->size);
 }
Beispiel #9
0
 /**
  * PIREPData::fileReport()
  * 
  * @param mixed $pirepdata
  * @return
  */
 public static function fileReport($pirepdata)
 {
     /*$pirepdata = array('pilotid'=>'',
       'code'=>'',
       'flightnum'=>'',
       'depicao'=>'',
       'arricao'=>'',
       'aircraft'=>'',
       'flighttime'=>'',
       'submitdate'=>'',
       'comment'=>'',
       'fuelused'=>'',
       'source'=>''
       'log'=>''
       );*/
     if (!is_array($pirepdata)) {
         return false;
     }
     $pirepdata['code'] = strtoupper($pirepdata['code']);
     $pirepdata['flightnum'] = strtoupper($pirepdata['flightnum']);
     $pirepdata['depicao'] = strtoupper($pirepdata['depicao']);
     $pirepdata['arricao'] = strtoupper($pirepdata['arricao']);
     /* Check if this PIREP was just submitted, check the last 10 minutes
      */
     if (Config::Get('PIREP_CHECK_DUPLICATE') == true) {
         $time_limit = Config::Get('PIREP_TIME_CHECK');
         if (empty($time_limit)) {
             $time_limit = 1;
         }
         $sql = "SELECT `pirepid` FROM " . TABLE_PREFIX . "pireps\n\t\t\t\t\tWHERE `pilotid` = {$pirepdata['pilotid']} \n\t\t\t\t\t\tAND `code` = '{$pirepdata['code']}'\n\t\t\t\t\t\tAND `flightnum` = '{$pirepdata['flightnum']}' \n\t\t\t\t\t\tAND DATE_SUB(NOW(), INTERVAL {$time_limit} MINUTE) <= `submitdate`";
         $res = DB::get_row($sql);
         if ($res) {
             self::$lasterror = 'This PIREP was just submitted!';
             return $res->pirepid;
         }
     }
     if ($pirepdata['depicao'] == '' || $pirepdata['arricao'] == '') {
         self::$lasterror = 'The departure or arrival airports are blank';
         return false;
     }
     # Check the aircraft
     if (!is_numeric($pirepdata['aircraft'])) {
         // Check by registration
         $ac = OperationsData::getAircraftByReg($pirepdata['aircraft']);
         if ($ac) {
             $pirepdata['aircraft'] = $ac->id;
         } else {
             // Check by name
             $ac = OperationsData::getAircraftByName($pirepdata['aircraft']);
             if ($ac) {
                 $pirepdata['aircraft'] = $ac->id;
             } else {
                 $pirepdata['aircraft'] = '0';
             }
         }
     }
     # Check the airports, add to database if they don't exist
     $depapt = OperationsData::getAirportInfo($pirepdata['depicao']);
     if (!$depapt) {
         $depapt = OperationsData::RetrieveAirportInfo($pirepdata['depicao']);
     }
     $arrapt = OperationsData::getAirportInfo($pirepdata['arricao']);
     if (!$arrapt) {
         $arrapt = OperationsData::RetrieveAirportInfo($pirepdata['arricao']);
     }
     # Look up the schedule
     $sched = SchedulesData::getScheduleByFlight($pirepdata['code'], $pirepdata['flightnum']);
     /*	Get route information, and also the detailed layout of the route
        Store it cached, in case the schedule changes later, then the route
        information remains intact. Also, if the nav data changes, then 
        the route is saved as it was 
        */
     if (!empty($pirepdata['route'])) {
         /*	They supplied some route information, so build up the data
            based on that. It needs a certain structure passed, so build that */
         $pirepdata['route'] = str_replace('SID', '', $pirepdata['route']);
         $pirepdata['route'] = str_replace('STAR', '', $pirepdata['route']);
         $pirepdata['route'] = str_replace('DCT', '', $pirepdata['route']);
         $pirepdata['route'] = trim($pirepdata['route']);
         $tmp = new stdClass();
         $tmp->deplat = $depapt->lat;
         $tmp->deplng = $depapt->lng;
         $tmp->route = $pirepdata['route'];
         $pirepdata['route_details'] = NavData::parseRoute($tmp);
         $pirepdata['route_details'] = serialize($pirepdata['route_details']);
         unset($tmp);
     }
     if (empty($pirepdata['route']) && !empty($sched->route)) {
         $pirepdata['route'] = $sched->route;
         $pirepdata['route'] = str_replace('SID', '', $pirepdata['route']);
         $pirepdata['route'] = str_replace('STAR', '', $pirepdata['route']);
         $pirepdata['route'] = str_replace('DCT', '', $pirepdata['route']);
         $pirepdata['route'] = trim($pirepdata['route']);
         /*	The schedule doesn't have any route_details, so let's populate
               the schedule while we're here. Then we'll use that same info
               to populate our details information 
            */
         if (empty($sched->route_details)) {
             $pirepdata['route_details'] = serialize(SchedulesData::getRouteDetails($sched->id));
         } else {
             /*	The schedule does have route information, and it's already been cached */
             $pirepdata['route_details'] = $sched->route_details;
         }
     }
     /*	This setting forces the next code to automatically
        calculate a load value for this current PIREP */
     if (Config::Get('PIREP_OVERRIDE_LOAD') == true) {
         $pirepdata['load'] == '';
     }
     # Check the load, if it's blank then look it up
     #	Based on the aircraft that was flown
     if (!isset($pirepdata['load']) || empty($pirepdata['load'])) {
         $pirepdata['load'] = FinanceData::getLoadCount($pirepdata['aircraft'], $sched->flighttype);
     }
     /* If the distance isn't supplied, then calculate it */
     if (!isset($pirepdata['distance']) || empty($pirepdata['distance'])) {
         $pirepdata['distance'] = OperationsData::getAirportDistance($depapt, $arrapt);
     }
     /* See if there's a landing rate */
     if (!isset($pirepdata['landingrate']) || empty($pirepdata['landingrate'])) {
         $pirepdata['landingrate'] = 0;
     }
     /* Any "raw" parameterized data which needs to be added */
     if (isset($pirepdata['rawdata'])) {
         $pirepdata['rawdata'] = serialize($pirepdata['rawdata']);
     } else {
         $pirepdata['rawdata'] = '';
     }
     /* Escape the comment field */
     //$pirepdata['log'] = DB::escape($pirepdata['log']);
     if (isset($pirepdata['comment'])) {
         $comment = DB::escape($pirepdata['comment']);
         unset($pirepdata['comment']);
     }
     /* Proper timestamp */
     $pirepdata['flighttime'] = str_replace(':', '.', $pirepdata['flighttime']);
     $pirepdata['flighttime_stamp'] = str_replace('.', ':', $pirepdata['flighttime']) . ':00';
     /* Export status as 0 */
     $pirepdata['exported'] = 0;
     $pirepdata['submitdate'] = 'NOW()';
     $pirepdata['modifieddate'] = 'NOW()';
     $pirepdata['accepted'] = PIREP_PENDING;
     $pirepdata['expenselist'] = '0';
     $pirepdata['flighttype'] = $sched->flighttype;
     # Do the insert based on the columns here
     $cols = array();
     $col_values = array();
     foreach ($pirepdata as $key => $value) {
         if ($key == 'submitdate') {
             $value = 'NOW()';
         } elseif ($key == 'comment') {
             continue;
         } else {
             $value = "'" . DB::escape($value) . "'";
         }
         $cols[] = "`{$key}`";
         $col_values[] = $value;
     }
     $cols = implode(', ', $cols);
     $col_values = implode(', ', $col_values);
     $sql = 'INSERT INTO ' . TABLE_PREFIX . "pireps ({$cols}) VALUES ({$col_values});";
     DB::query($sql);
     $pirepid = DB::$insert_id;
     // Add the comment if its not blank
     if ($comment != '') {
         self::addComment($pirepid, $pirepdata['pilotid'], $comment);
     }
     # Update the financial information for the PIREP, true to refresh fuel
     self::PopulatePIREPFinance($pirepid, true);
     # Do other assorted tasks that are along with a PIREP filing
     # Update the flown count for that route
     self::UpdatePIREPFeed();
     # Update any pilot's information
     $pilotinfo = PilotData::getPilotData($pirepdata['pilotid']);
     $pilotcode = PilotData::getPilotCode($pilotinfo->code, $pilotinfo->pilotid);
     PilotData::UpdateLastPIREPDate($pilotinfo->pilotid);
     if (Config::Get('EMAIL_SEND_PIREP') === true) {
         # Send an email to the admin that a PIREP was submitted
         $sub = "A PIREP has been submitted by {$pilotcode} ({$pirepdata['depicao']} - {$pirepdata['arricao']})";
         $message = "A PIREP has been submitted by {$pilotcode} " . "({$pilotinfo->firstname} {$pilotinfo->lastname})\n\n" . "{$pirepdata['code']}{$pirepdata['flightnum']}: {$pirepdata['depicao']} to {$pirepdata['arricao']}\n" . "Aircraft: {$pirepdata['aircraft']}\n" . "Flight Time: {$pirepdata['flighttime']}\n" . "Landing Rate: {$pirepdata['landingrate']}\n" . "Filed using: {$pirepdata['source']}\n\n" . "Comment: {$comment}\n\n" . "Click to approve this pirep (admin must be signed in):\n" . adminurl('/pirepadmin/approvepirep/' . $pirepid);
         $email = Config::Get('EMAIL_NEW_PIREP');
         if (empty($email)) {
             $email = ADMIN_EMAIL;
         }
         Util::SendEmail($email, $sub, $message);
     }
     /* Add this into the activity feed */
     $message = Lang::get('activity.new.pirep');
     foreach ($pirepdata as $key => $value) {
         $message = str_replace('$' . $key, $value, $message);
     }
     # Add it to the activity feed
     ActivityData::addActivity(array('pilotid' => $pirepdata['pilotid'], 'type' => ACTIVITY_NEW_PIREP, 'refid' => $pirepid, 'message' => htmlentities($message)));
     /* Now send data to vaCentral */
     CentralData::send_pirep($pirepid);
     // Reset this ID back
     DB::$insert_id = $pirepid;
     self::$pirepid = $pirepid;
     return $pirepid;
 }
Beispiel #10
0
<?php

include dirname(__FILE__) . '/bootstrap.inc.php';
echo '<pre>';
Config::set('TWITTER_AIRLINE_ACCOUNT', 'nabeels');
Config::set('TWITTER_ENABLE_PUSH', false);
ActivityData::readTwitter();
// Push a test message to Twitter
Config::set('TWITTER_ENABLE_PUSH', true);
$pirep = PIREPData::getRecentReportsByCount(20);
$idx = rand(0, count($pirep) - 1);
$pirep = $pirep[$idx];
$message = Lang::get('activity.new.pirep');
foreach ($pirep as $key => $value) {
    $message = str_replace('$' . $key, $value, $message);
}
# Push a new PIREP
$ret = ActivityData::pushToTwitter(array('pilotid' => $pirep->pilotid, 'type' => ACTIVITY_NEW_PIREP, 'refid' => $pirep->pirepid, 'message' => $message));
var_dump($ret);
 public function executePost(sfWebRequest $request)
 {
     $form = new sfForm();
     $token = $form->getCSRFToken();
     if ($token = !$request->getParameter('CSRFtoken')) {
         $json = array('status' => 'error', 'message' => 'Error. Invalid CSRF token Key.');
         return $this->renderText(json_encode($json));
     }
     if (!$request->getParameter('body')) {
         $json = array('status' => 'error', 'message' => 'Error. Body is null.');
         return $this->renderText(json_encode($json));
     }
     $activity = new ActivityData();
     $activity->setMemberId($this->getUser()->getMemberId());
     $activity->setBody($request->getParameter('body'));
     $mentions = opTimelinePluginUtil::hasScreenName($request->getParameter('body'));
     if (!is_null($mentions)) {
         $activity->setTemplate('mention_member_id');
         $activity->setTemplateParam($mentions);
     }
     $inReplyToActivityId = $request->getParameter('replyId');
     if (isset($inReplyToActivityId) && is_numeric($inReplyToActivityId)) {
         $activity->setInReplyToActivityId($inReplyToActivityId);
     }
     $foreign = $request->getParameter('foreign');
     $foreignId = $request->getParameter('foreignId');
     if (isset($foreign) && isset($foreignId) && is_numeric($foreignId)) {
         $activity->setForeignTable($foreign);
         $activity->setForeignId($foreignId);
     }
     $activity->setPublicFlag(1);
     $activity->save();
     $json = array('status' => 'success', 'message' => 'UPDATE was succeed!');
     return $this->renderText(json_encode($json));
 }
Beispiel #12
0
 /**
  * @brief deletes an  object with the data provided by \Sabredav
  * @param integer $cid calendar id
  * @param string $uri the uri of the object
  * @return boolean
  */
 public static function deleteFromDAVData($cid, $uri)
 {
     $oldobject = self::findWhereDAVDataIs($cid, $uri);
     $calendar = Calendar::find($cid);
     if ($calendar['userid'] != \OCP\User::getUser()) {
         $sharedCalendar = \OCP\Share::getItemSharedWithBySource(App::SHARECALENDAR, App::SHARECALENDARPREFIX . $cid);
         if (!$sharedCalendar || !($sharedCalendar['permissions'] & \OCP\PERMISSION_DELETE)) {
             throw new VObject_DAV_Exception_Forbidden(App::$l10n->t('You do not have the permissions to delete this event.'));
         }
     }
     $stmt = \OCP\DB::prepare('DELETE FROM `' . App::CldObjectTable . '` WHERE `calendarid`= ? AND `uri`=?');
     $stmt->execute(array($cid, $uri));
     Calendar::touchCalendar($cid);
     \OCP\Util::emitHook('\\OCA\\CalendarPlus', 'deleteEvent', $oldobject['id']);
     $params = array('mode' => 'deleted', 'link' => '', 'trans_type' => App::$l10n->t($oldobject['objecttype']), 'summary' => $oldobject['summary'], 'cal_user' => $calendar['userid'], 'cal_displayname' => $calendar['displayname']);
     ActivityData::logEventActivity($params, true);
     return true;
 }
 public function executeUpdateActivity($request)
 {
     if ($request->isMethod(sfWebRequest::POST)) {
         $this->forward404Unless(opConfig::get('is_allow_post_activity'));
         $newObject = new ActivityData();
         $newObject->setMemberId($this->getUser()->getMemberId());
         $this->form = new ActivityDataForm($newObject);
         $params = $request->getParameter('activity_data');
         $this->form->bind($params);
         if ($this->form->isValid()) {
             $this->form->save();
             if ($request->isXmlHttpRequest()) {
                 $activities = Doctrine::getTable('ActivityData')->getFriendActivityList();
                 $this->getContext()->getConfiguration()->loadHelpers('Partial');
                 return $this->renderText(get_partial('default/activityRecord', array('activity' => $this->form->getObject())));
             } else {
                 $this->redirect($params['next_uri']);
             }
         } else {
             if ($request->isXmlHttpRequest()) {
                 $this->getResponse()->setStatusCode(500);
             } else {
                 $this->getUser()->setFlash('error', 'Failed to post activity.');
                 if (isset($params['next_uri'])) {
                     $this->redirect($params['next_uri']);
                 }
                 $this->redirect('@homepage');
             }
         }
     }
     return sfView::NONE;
 }
 public function executePost(sfWebRequest $request)
 {
     $this->getResponse()->setContentType('application/json');
     if ($token = !$request->getParameter('body')) {
         $this->status = 'error';
         $this->message = 'Error. Body is null.';
         return sfView::SUCCESS;
     }
     $activity = new ActivityData();
     $activity->setMemberId($this->getMember()->getId());
     $activity->setBody(htmlspecialchars($request->getParameter('body'), ENT_QUOTES));
     $mentions = opTimelinePluginUtil::hasScreenName($request->getParameter('body'));
     if (!is_null($mentions)) {
         $activity->setTemplate('mention_member_id');
         $activity->setTemplateParam($mentions);
     }
     $inReplyToActivityId = $request->getParameter('replyId');
     if (isset($inReplyToActivityId) && is_numeric($inReplyToActivityId)) {
         $activity->setInReplyToActivityId($inReplyToActivityId);
     }
     $foreign = $request->getParameter('foreign');
     $foreignId = $request->getParameter('foreignId');
     if (isset($foreign) && isset($foreignId) && is_numeric($foreignId)) {
         $activity->setForeignTable($foreign);
         $activity->setForeignId($foreignId);
     }
     $activity->setPublicFlag(1);
     $activity->save();
     $this->status = 'success';
     $this->message = "Update request was suceed!";
     return sfView::SUCCESS;
 }
Beispiel #15
0
 public static function calculateUpdatePilotRank($pilotid, $ranks_list = null)
 {
     /* Don't calculate a pilot's rank if this is set */
     if (Config::Get('RANKS_AUTOCALCULATE') == false) {
         return;
     }
     if ($ranks_list === null) {
         $ranks_list = self::getAllRanks();
     }
     $pilotid = intval($pilotid);
     $pilot = PilotData::getPilotData($pilotid);
     $pilothours = $pilot->totalhours;
     if (Config::Get('TRANSFER_HOURS_IN_RANKS') == true) {
         $pilothours += $pilot->transferhours;
     }
     $i = 0;
     foreach ($ranks_list as $rank) {
         $i++;
         if ($pilothours >= intval($rank->minhours)) {
             $rank_level = $i;
             $last_rank = $rank->rank;
             $last_rankid = $rank->rankid;
         }
     }
     $update = array('rankid' => $last_rankid, 'rank' => $last_rank, 'ranklevel' => $rank_level);
     PilotData::updateProfile($pilot->pilotid, $update);
     if ($pilot->rank != $last_rank) {
         $message = Lang::get('activity.pilot.promotion');
         $message = str_replace('$rank', $last_rank, $message);
         # Add it to the activity feed
         ActivityData::addActivity(array('pilotid' => $pilotid, 'type' => ACTIVITY_PROMOTION, 'refid' => $pilotid, 'message' => htmlentities($message)));
     }
 }
 /**
  * Add a  User
  * 
  * $data = array(
  * 'firstname' => '',
  * 'lastname' => '',
  * 'email' => '',
  * 'password' => '',
  * 'code' => '',
  * 'location' => '',
  * 'hub' => '',
  * 'confirm' => false);
  */
 public static function addUser($data)
 {
     /*$data = array(
       'firstname' => '',
       'lastname' => '',
       'email' => '',
       'password' => '',
       'code' => '',
       'location' => '',
       'hub' => '',
       'confirm' => false);*/
     $exists = self::CheckUserEmail($data['email']);
     if (is_object($exists)) {
         self::$error = 'Email already exists';
         return false;
     }
     //Set the password, add some salt
     $salt = md5(date('His'));
     $password = md5($data['password'] . $salt);
     //Stuff it into here, the confirmation email will use it.
     self::$salt = $salt;
     $code = DB::escape(strtoupper($data['code']));
     $firstname = DB::escape(ucwords($data['firstname']));
     $lastname = DB::escape(ucwords($data['lastname']));
     $location = DB::escape(strtoupper($data['location']));
     //Add this stuff in
     if ($data['confirm'] === true) {
         $confirm = 1;
     } else {
         $confirm = 0;
     }
     $sql = "INSERT INTO " . TABLE_PREFIX . "pilots (firstname, lastname, email,\n\t\t\t\t\tcode, location, hub, password, salt, confirmed, joindate, lastip)\n\t\t\t\t  VALUES (\n                    '{$firstname}', '{$lastname}', '{$data['email']}', '{$code}',\n\t\t\t\t\t'{$location}', '{$data['hub']}', '{$password}', \n                    '{$salt}', {$confirm}, NOW(), \n                    '{$_SERVER['REMOTE_ADDR']}'\n                    )";
     $res = DB::query($sql);
     if (DB::errno() != 0) {
         if (DB::errno() == 1062) {
             self::$error = 'This email address is already registered';
             return false;
         }
         self::$error = DB::error();
         return false;
     }
     //Grab the new pilotid, we need it to insert those "custom fields"
     $pilotid = DB::$insert_id;
     RanksData::CalculateUpdatePilotRank($pilotid);
     PilotData::generateSignature($pilotid);
     /* Add them to the default group */
     $defaultGroup = SettingsData::getSettingValue('DEFAULT_GROUP');
     PilotGroups::addUsertoGroup($pilotid, $defaultGroup);
     // For later
     self::$pilotid = $pilotid;
     //Get customs fields
     $fields = self::getCustomFields();
     if (count($fields) > 0) {
         foreach ($fields as $field) {
             $value = Vars::POST($field->fieldname);
             $value = DB::escape($value);
             if ($value != '') {
                 $sql = "INSERT INTO `" . TABLE_PREFIX . "fieldvalues` (fieldid, pilotid, value)\n    \t\t\t\t\t\t\tVALUES ({$field->fieldid}, {$pilotid}, '{$value}')";
                 DB::query($sql);
             }
         }
     }
     $pilotdata = PilotData::getPilotData($pilotid);
     /* Add this into the activity feed */
     $message = Lang::get('activity.new.pilot');
     foreach ($pilotdata as $key => $value) {
         $message = str_replace('$' . $key, $value, $message);
     }
     # Add it to the activity feed
     ActivityData::addActivity(array('pilotid' => $pilotid, 'type' => ACTIVITY_NEW_PILOT, 'refid' => $pilotid, 'message' => htmlentities($message)));
     return true;
 }