/**
  * Subscribe to a plan (= no current active plan)
  * WARNING, you should ensure the user can subscribe before calling this: use canSubscribe() and canSubscribeTo()
  * @param User $use The user who buy the plan, and will use it 
  * @param WpPlan $plan
  * @param WpInvitation $invitation Optional
  * @return WpSubscription the newly created subscription if ok, or null if an error occured (db error)
  */
 public static function subscribe($user, $plan, $invitation = null)
 {
     if ($user === null || !$user instanceof User || $plan === null || !$plan instanceof WpPlan) {
         throw new MWException('Cannot subscribe, invalid argument.');
     }
     $invitationId = 0;
     if ($invitation instanceof WpInvitation) {
         $invitationId = $invitation->getId();
     }
     $user_id = $user->getId();
     $db_master = $dbw = wfGetDB(DB_MASTER);
     // archive the current sub if necessary
     // not that even if this sub is active, it will be archived
     // so, be sure that you need to call this subscribe() !
     $current_sub = self::newByUserId($user_id);
     $tmr = self::createTMR($user_id, $user->getEmail(), $plan, WP_SUBSCRIPTION_TMR_TYPE_NEW);
     // already paid, or waiting a payment ?
     switch ($tmr['tmr_status']) {
         case 'OK':
             // already paid by user
             $now = self::now();
             $end = self::calculateEndDateFromStart($now, $plan->getPeriod());
             $renewal_plan_id = $plan->getRenewalPlan($end)->getId();
             if ($current_sub != null) {
                 $current_sub->archive();
                 $current_sub->update($plan->getId(), $user_id, $tmr['tmr_id'], 'OK', $now, $end, true, $renewal_plan_id, false, $invitationId, $db_master);
                 $sub = $current_sub;
             } else {
                 $sub = self::create($plan->getId(), $user_id, $tmr['tmr_id'], 'OK', $now, $end, true, $renewal_plan_id, false, $invitationId, $db_master);
             }
             if ($sub == null) {
                 return null;
             }
             self::addSubscribersGroupToUser($user);
             $sub->sendOnFirstActivation();
             return $sub;
         case 'PE':
             // waiting payment
             if ($current_sub != null) {
                 $current_sub->archive();
                 $current_sub->update($plan->getId(), $user_id, $tmr['tmr_id'], 'PE', null, null, false, WPP_ID_NORENEW, false, $invitationId, $db_master);
                 $sub = $current_sub;
             } else {
                 $sub = self::create($plan->getId(), $user_id, $tmr['tmr_id'], 'PE', null, null, false, WPP_ID_NORENEW, false, $invitationId, $db_master);
             }
             return $sub;
     }
     // if we arrive here, the payment status is unknown
     wfDebugLog('wikiplaces', 'WpSubscription::subscribe() ERROR the transaction status is not handled: "' . $tmr['tmr_status'] . '" of tmr_id[' . $tmr['tmr_id'] . ']');
     return null;
 }