<?php
  /**
   * Users Class
   *
   * @package Wojo Framework
   * @author wojoscripts.com
   * @copyright 2019
   * @version $Id: user.class.php, v1.00 201-10-20 18:20:24 gewa Exp $
   */
  if (!defined("_WOJO"))
      die('Direct access to this location is not allowed.');


  class Users
  {

      const mTable = "users";
      const rTable = "roles";
      const rpTable = "role_privileges";
      const pTable = "privileges";
	  const blTable = 'banlist';
	  const aTable = 'activity';
	  

      /**
       * Users::__construct()
       * 
       * @return
       */
      public function __construct()
      {

      }

      /**
       * Users::Index()
       * 
       * @return
       */
      public function Index($from = false)
      {
		  
          if (isset($_GET['letter']) and (isset($_POST['fromdate']) && $_POST['fromdate'] <> "" || isset($from) && $from != '')) {
              $enddate = date("Y-m-d");
              $letter = Validator::sanitize($_GET['letter'], 'default', 2);
              $fromdate = (empty($from)) ? Validator::sanitize($_POST['fromdate']) : $from;
			  $fromdate = Db::toDate($fromdate, false);
              if (isset($_POST['enddate']) && $_POST['enddate'] <> "") {
                  $enddate = Validator::sanitize($_POST['enddate']);
				  $enddate = Db::toDate($enddate, false);
              }
              $and = "AND c.created BETWEEN '" . $fromdate . "' AND '" . $enddate . " 23:59:59' AND c.name REGEXP '^" . $letter . "'";

          } elseif (isset($_POST['fromdate']) && $_POST['fromdate'] <> "" || isset($from) && $from != '') {
              $enddate = date("Y-m-d");
              $fromdate = (empty($from)) ? Validator::sanitize($_POST['fromdate']) : $from;
			  $fromdate = Db::toDate($fromdate, false);
              if (isset($_POST['enddate']) && $_POST['enddate'] <> "") {
                  $enddate = Validator::sanitize($_POST['enddate']);
				  $enddate = Db::toDate($enddate, false);
              }
              $and = "AND c.created BETWEEN '" . $fromdate . "' AND '" . $enddate . " 23:59:59'";

          } elseif (isset($_GET['letter'])) {
              $letter = Validator::sanitize($_GET['letter'], 'default', 2);
              $and = "AND c.name REGEXP '^" . $letter . "' OR u.fname REGEXP '^" . $letter . "' OR u.lname REGEXP '^" . $letter . "'";
          } else {
              $and = null;
          }
		  
          if (isset($_GET['order'])) {
              list($sort, $order) = explode("/", $_GET['order']);
              $sort = Validator::sanitize($sort, "default", 14);
              $order = Validator::sanitize($order, "default", 4);
              if (in_array($sort, array(
                  "name",
                  "city",
                  "email",
				  "currency",
                  "created"))) {
                  $ord = ($order == 'DESC') ? " DESC" : " ASC";
                  $sorting = $sort . $ord;
              } else {
                  $sorting = " c.owner DESC, c.name, u.userlevel DESC";
              }
          } else {
              $sorting = " c.owner DESC, c.name, u.userlevel DESC";
          }
		  
		  $sql = "
		  SELECT 
			c.id,
			c.name,
			c.created AS cdate,
			c.address,
			c.email AS cmail,
			c.logo,
			c.owner,
			CONCAT(u.fname, ' ', u.lname) AS fullname,
			u.id AS mid,
			u.userlevel,
			u.avatar,
			u.active,
			u.invite_by,
			u.invite_on,
			u.email
		  FROM
			`" . Company::cTable . "`  AS c 
			LEFT JOIN `" . self::mTable . "` AS u 
			  ON u.company = c.id 
		  WHERE c.status = ?
		  $and 
		  ORDER BY $sorting;";
		  $query = Db::run()->pdoQuery($sql, array(1))->results();
		  
		  $sql2 = "
		  SELECT 
			CONCAT(u.fname, ' ', u.lname) AS fullname,
			u.id,
			u.userlevel,
			u.avatar,
			u.active,
			u.invite_by,
			u.invite_on,
			u.email
		  FROM
			`" . self::mTable . "`  AS u 
		  WHERE u.status = ?
		  AND u.company = ?
		  ORDER BY u.fname;";
		  $query2 = Db::run()->pdoQuery($sql2, array(1, 0))->results();
		  
		  $data = array();
		  if ($query) {
			  $cid = null;
			  foreach ($query as $i => $row) {
				  if ($cid != $row->name) {
					  $cid = $row->name;
					  $data['hcmp'][$row->id]['name'] = $row->name;
					  $data['hcmp'][$row->id]['address'] = $row->address;
					  $data['hcmp'][$row->id]['logo'] = $row->logo;
					  $data['hcmp'][$row->id]['cdate'] = $row->cdate;
					  $data['hcmp'][$row->id]['owner'] = $row->owner;
					  $data['hcmp'][$row->id]['id'] = $row->id;
				  }
				  $data['hcmp'][$row->id]['members'][$i]['fullname'] = $row->fullname;
				  $data['hcmp'][$row->id]['members'][$i]['avatar'] = $row->avatar;
				  $data['hcmp'][$row->id]['members'][$i]['email'] = $row->email;
				  $data['hcmp'][$row->id]['members'][$i]['userlevel'] = $row->userlevel;
				  $data['hcmp'][$row->id]['members'][$i]['invite_on'] = $row->invite_on; 
				  $data['hcmp'][$row->id]['members'][$i]['invite_by'] = $row->invite_by; 
				  $data['hcmp'][$row->id]['members'][$i]['active'] = $row->active; 
				  $data['hcmp'][$row->id]['members'][$i]['uid'] = $row->mid;
			  }
		  }
		  
		  $data['ncmp'] = $query2 ? $query2 : null;
		  
		  $tpl = App::View(BASEPATH . 'view/');
		  $tpl->dir = "admin/";
		  $tpl->template = 'admin/members.tpl.php'; 
		  $tpl->title = Lang::$word->MAC_TITLE;
		  $tpl->crumbs = ['admin', Lang::$word->NAV_1];
		  $tpl->data = $data;
	  }

	  /**
	   * Users::invitePople()
	   * 
	   * @return
	   */
	  public function invitePople()
	  {

		  $filters = array(
			  'role' => 'string',
			  'company' => 'numbers'
			  );
	
		  if (!array_filter($_POST['email'])) {
			  Message::$msgs['email'] = LANG::$word->MAC_ONEMAIL;
		  }
		  
		  if(array_filter($_POST['email'])) {
			  $pemails = array_filter($_POST['email']);
			  $in_string = '';
			  foreach ($pemails as $i => $email ) {
				  $in_string .= "'" . Validator::sanitize($email, "emailalt") . "',";
			  }
			  $in_string = substr($in_string, 0, -1);

			  $sql = "SELECT email, CONCAT(fname,' ',lname) as name  FROM `" . self::mTable . "` WHERE email IN (" . $in_string . ")";
			  if($emails = Db::run()->pdoQuery($sql)->results()) {
				  $res = '<ul>';
				  foreach ($emails as $value) {
					  $res .= '<li>' . $value->email . ' - ' . $value->name . '</li>';
				  }
				  $res .= '</ul>';
				  Message::$msgs['email'] = LANG::$word->MAC_MAILIN_USE . $res;
			  }
		  }
		  
		  $validate = Validator::instance();
		  $safe = $validate->doFilter($_POST, $filters);
		  
		  if (empty(Message::$msgs)) {
			  $emails = array_filter($_POST['email']);
			  foreach ($emails as $email) {
				  $dataArray[] = array(
					  'username' => $email,
					  'email' => $email,
					  'company' => ($safe->company) ? $safe->company : 0,
					  'type' => $safe->role,
					  'userlevel' => ($safe->role == "owner" ? 9 : ($safe->role == "staff" ? 8 : 1)),
					  'status' => 1,
					  'active' => "t",
					  'invite_by' => Auth::$userdata->fname . ' ' . Auth::$userdata->lname,
					  'invite_on' => Db::toDate(),
					  'invite_token' => Utility::randomString(32)
					  );
			  }
			  $last_id = Db::run()->insertBatch(self::mTable, $dataArray)->getAllLastInsertId();
	
			  if (isset($_POST['projects'])) {
				  foreach ($last_id as $uid) {
					  foreach ($_POST['projects'] as $k => $pid) {
						  $datapArray[] = array(
							  'user_id' => $uid,
							  'project_id' => $pid,
							  );
					  }
				  }
				  Db::run()->insertBatch(Project::pxTable, $datapArray);
			  }
	
	          $tpl = Db::run()->first(Content::eTable, array("body", "subject"), array('typeid' => 'userInvite'));
			  $mailer = Mailer::sendMail();
			  $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100, 30));
			  $replacements = array();
			  $numSent = 0;
			  $failedRecipients = array();
			  
			  $core = App::Core();
			  $userrow = Db::run()->pdoQuery("SELECT email, invite_token FROM `" . self::mTable . "` WHERE id IN(" . Utility::implodeFields($last_id) . ")")->results();
	
			  foreach ($userrow as $cols) {
				  $replacements[$cols->email] = array(
					  '[LOGO]' => Utility::getLogo(),
					  '[EMAIL]' => $cols->email,
					  '[DATE]' => date('Y'),
					  '[COMPANY]' => $core->company,
					  '[LOGINURL]' => Url::url('/join', $cols->invite_token),
					  '[SITEURL]' => SITEURL,
					  '[CEMAIL]' => $core->site_email,
					  '[FB]' => $core->social->facebook,
					  '[TW]' => $core->social->twitter,
					  );
			  }
	
			  $decorator = new Swift_Plugins_DecoratorPlugin($replacements);
			  $mailer->registerPlugin($decorator);

			  $message = Swift_Message::newInstance()
						->setSubject(str_replace("[COMPANY]", $core->company, $tpl->subject))
						->setFrom(array($core->site_email => $core->company))
						->setBody($tpl->body, 'text/html');

			  foreach ($userrow as $row) {
				  $message->setTo(array($row->email));
				  $numSent++;
				  $mailer->send($message, $failedRecipients);
				  
				  $dataAcArray[] = array(
				      'uid' => App::Auth()->uid,
					  'type' => "Members",
					  'groups' => "invite",
					  'fullname' => $row->email,
					  'is_activity' => 1,
					  'ip' => Url::getIP()
					  );
			  }
			  Db::run()->insertBatch(self::aTable, $dataAcArray);

			  unset($row);

			  if ($numSent) {
				  $json['type'] = 'success';
				  $json['title'] = Lang::$word->SUCCESS;
				  $json['message'] = $numSent . ' ' . Lang::$word->MAC_SENDINV_OK;
				  $json['redirect'] = Url::url("/admin/members");
			  } else {
				  $json['type'] = 'error';
				  $json['title'] = Lang::$word->ERROR;
				  $res = '';
				  $res .= '<ul class="wojo list">';
				  foreach ($failedRecipients as $failed) {
					  $res .= '<li>' . $failed . '</li>';
				  }
				  $res .= '</ul>';
				  $json['message'] = Lang::$word->EMN_ALERT . $res;
				  }
			  print json_encode($json);
		  } else {
			  Message::msgSingleStatus();
		  }
	  }

      /**
       * Users::Archive()
       * 
       * @return
       */
	  public function Archive()
	  {
		  $tpl = App::View(BASEPATH . 'view/');
		  $tpl->dir = "admin/";
		  $tpl->title = Lang::$word->MAC_ARCHIVE;
		  $tpl->members = $this->getArchivedMembers();
		  $tpl->companies = App::Company()->getArchivedCompanies();
		  $tpl->crumbs = ['admin', Lang::$word->NAV_1, Lang::$word->NAV_3];
		  $tpl->template = 'admin/members.tpl.php';
	  }
	  
      /**
       * Users::Details()
       * 
	   * @param int $id
       * @return
       */
	  public function Details($id)
	  {
		  
		  $tpl = App::View(BASEPATH . 'view/');
		  $tpl->dir = "admin/";
		  $tpl->title = Lang::$word->MAC_TITLE2;
		  $tpl->crumbs = ['admin', Lang::$word->NAV_1, Lang::$word->NAV_16];
	
		  if (!$row = Db::run()->first(self::mTable, null, array("id =" => $id))) {
			  $tpl->template = 'admin/error.tpl.php';
			  $tpl->error = DEBUG ? "Invalid ID ($id) detected [users.class.php, ln.:" . __line__ . "]" : Lang::$word->META_ERROR;
		  } else {
			  $tpl->row = $row;
			  $tpl->data = Utility::groupToLoop($this->getUserActivity($id), "day");
			  $tpl->template = 'admin/members.tpl.php';
		  }
	  }

      /**
       * Users::invite()
       * 
       * @return
       */
	  public function Invite()
	  {
		  $tpl = App::View(BASEPATH . 'view/');
		  $tpl->dir = "admin/";
		  $tpl->title = Lang::$word->MAC_INVPEOPLE;
		  $tpl->projects = App::Project()->getProjects();
		  $tpl->companies = App::Company()->getCompanies();
		  $tpl->crumbs = ['admin', Lang::$word->NAV_1, Lang::$word->NAV_4];
		  $tpl->template = 'admin/members.tpl.php';
	  }

      /**
       * Users::Activity()
       * 
       * @return
       */
      public function Activity()
      {
		  
		  $tpl = App::View(BASEPATH . 'view/');
		  $tpl->dir = "admin/";
		  $tpl->template = 'admin/activity.tpl.php'; 
		  $tpl->title = Lang::$word->ACT_TITLE;
		  $tpl->data = $this->getAllUserActivity(Date::doDate("yyyy-MM-dd", Date::today()));
	  }
	  
      /**
       * Users::getUserActivity()
       * 
	   * @param int $id
       * @return
       */
      public function getUserActivity($id)
      {
		  
		  $sql = "
		  SELECT 
			*,
			DATE(created) AS day,
			TIME(created) AS hour 
		  FROM
			`" . self::aTable . "` 
		  WHERE uid = ?
		  AND is_activity = ?
		  ORDER BY created DESC;";
		  
		  $row = Db::run()->pdoQuery($sql, array($id, 1))->results();
		  
		  return ($row) ? $row : 0;
      }

      /**
       * Users::getAllUserActivity()
       * 
	   * @param str $date
       * @return
       */
      public function getAllUserActivity($date)
      {
		  
		  $sql = "
		  SELECT 
			*,
			DATE(created) AS cdate,
			TIME(created) AS hour 
		  FROM
			`" . self::aTable . "` 
		  WHERE uid = ?
		  AND DATE(created) = ?
		  ORDER BY created DESC;";
		  
		  $row = Db::run()->pdoQuery($sql, array(App::Auth()->uid, $date))->results();
		  
		  return ($row) ? $row : 0;

      }
	  
      /**
       * Users::addSmallActivity()
       * 
	   * @param array $data
       * @return
       */
      public static function addSmallActivity($data)
      {

		  $data2 = array(
			  'username' => App::Auth()->username,
			  'fullname' => App::Auth()->name,
			  );
		  $result = array_merge($data, $data2);

		  Db::run()->insert(self::aTable, $result);

      }
	  
      /**
       * Users::getArchivedMembers()
       * 
       * @return
       */
      public function getArchivedMembers()
      {
          $sql = "
		  SELECT 
			*,
			CONCAT(fname, ' ', lname) AS name 
		  FROM `" . self::mTable . "` 
		  WHERE status = ? 
		  ORDER BY fname;";
          $row = Db::run()->pdoQuery($sql, array(3))->results();

          return ($row) ? $row : 0;
      }
	  
      /**
       * Users::activityStatus()
       * 
       * @param array $array
       * @return
       */
      public static function activityStatus($array)
      {
          switch ($array->groups) {
              case "invoice":
				  return Lang::$word->ACT_CRINV . ' <a href="' . Url::url("/admin/invoices/view", $array->invoice_id) . '">' .  $array->title. ' </a>';
				  break;
              case "estimate":
				  return Lang::$word->ACT_CREST . ' <a href="' . Url::url("/admin/estimates/view", $array->estimate_id) . '">' .  $array->title. ' </a>';
				  break;
              case "invite":
                  return Lang::$word->ACT_INVUSR . ' <a href="' . Url::url("/admin/members/details", $array->userid) . '">' .  $array->comment. ' </a>';
				  break;
              case "company":
                  return Lang::$word->ACT_CRCOMPANY . ' <a href="' . Url::url("/admin/companies/view", $array->company_id) . '">' .  $array->title. ' </a>';
				  break;
              case "project":
                  return Lang::$word->ACT_CRPROJECT . ' <a href="' . Url::url("/admin/projects/view", $array->project_id) . '">' .  $array->title. ' </a>';
				  break;
              case "projectc":
                  return Lang::$word->ACT_CRPROJECTC . ' <a href="' . Url::url("/admin/projects/view", $array->project_id) . '">' .  $array->title. ' </a>';
				  break;
              case "task":
                  return Lang::$word->ACT_CRTASK . ' <a href="' . Url::url("/admin/tasks", $array->task_id) . '">' .  $array->title. ' </a>';
				  break;
              case "team":
                  return Lang::$word->ACT_CRTEAM . ' <a href="' . Url::url("/admin/teams") . '">' .  $array->title. ' </a>';
				  break;
              case "message":
                  return Lang::$word->ACT_CRDIS . ' <a href="' . Url::url("/admin/discussions/" . $array->project_id, $array->message_id) . '">' .  $array->title. ' </a>';
				  break;
              case "note":
                  return Lang::$word->ACT_CRNOTE . ' <a href="' . Url::url("/admin/notes/" . $array->project_id, $array->note_id) . '">' .  $array->title. ' </a>';
				  break;
              case "file":
				  return Lang::$word->ACT_UPLFILE . ' <a href="' . Url::url("/admin/projects/files", $array->project_id) . '">' .  $array->title. ' </a>';
				  break;
              case "calendar":
				  return Lang::$word->ACT_CRCAL . ' <a href="' . Url::url("/admin/calendar") . '">' .  $array->title. ' </a>';
				  break;
              default:
                  return '';
				  break;
          }
      }

      /**
       * Users::activityStatusFront()
       * 
       * @param array $array
       * @return
       */
      public static function activityStatusFront($array)
      {
          switch ($array->groups) {
              case "invoice":
				  return Lang::$word->ACT_CRINV . ' ' .  $array->title;
				  break;
              case "estimate":
				  return Lang::$word->ACT_CREST . ' ' .  $array->title;
				  break;
              case "invite":
                  return Lang::$word->ACT_INVUSR . ' ' .  $array->comment;
				  break;
              case "company":
                  return Lang::$word->ACT_CRCOMPANY . ' ' .  $array->title;
				  break;
              case "project":
                  return Lang::$word->ACT_CRPROJECT . ' ' .  $array->title;
				  break;
              case "projectc":
                  return Lang::$word->ACT_CRPROJECTC . ' ' .  $array->title;
				  break;
              case "task":
                  return Lang::$word->ACT_CRTASK . ' ' .  $array->title;
				  break;
              case "team":
                  return Lang::$word->ACT_CRTEAM . ' ' .  $array->title;
				  break;
              case "message":
                  return Lang::$word->ACT_CRDIS . ' ' .  $array->title;
				  break;
              case "note":
                  return Lang::$word->ACT_CRNOTE . ' ' .  $array->title;
				  break;
              case "file":
				  return Lang::$word->ACT_UPLFILE . ' ' .  $array->title;
				  break;
              case "calendar":
				  return Lang::$word->ACT_CRCAL . ' ' .  $array->title;
				  break;
              default:
                  return '';
				  break;
          }
      }
	  
      /**
       * Users::activityTypeStatus()
       * 
       * @param mixed $type
       * @return
       */
      public static function activityTypeStatus($type)
      {
          switch ($type) {
              case "Invoices":
                  return Lang::$word->INV_INVOICES;
				  break;

              case "Estimates":
                  return Lang::$word->EST_ESTIMATES;
				  break;
              case "Teams":
                  return Lang::$word->TMS_TEAMS;
				  break;
              case "Members":
                  return Lang::$word->PEOPLE;
				  break;
              case "Companies":
                  return Lang::$word->CMP_COMPANIES;
				  break;
              case "Tasks":
                  return Lang::$word->TSK_TASKS;
				  break;
              case "Notes":
                  return Lang::$word->NOT_NOTES;
				  break;
              case "Projects":
                  return Lang::$word->PRJ_PROJECTS;
				  break;
              case "Calendar":
                  return Lang::$word->CAL_CALENDAR;
				  break;
          }
      }
	  
      /**
       * Users::resendInvitation()
       * 
       * @return
       */
      public function resendInvitation()
      {

		  $row = Db::run()->first(Users::mTable, array("email", "invite_token", "id"), array('id' => Filter::$id));
		  $tpl = Db::run()->first(Content::eTable, array("body", "subject"), array('typeid' => 'userInvite'));

		  $data = array(
			  'invite_by' => Auth::$userdata->fname . ' ' . Auth::$userdata->lname,
			  'invite_on' => Db::toDate(),
			  'invite_token' => Utility::randomString(32),
			  );
		  Db::run()->update(self::mTable, $data, array("id" => $row->id));
			  
		  $mailer = Mailer::sendMail();
		  $core = App::Core();
		  
		  $body = str_replace(array(
			  '[LOGO]',
			  '[EMAIL]',
			  '[DATE]',
			  '[COMPANY]',
			  '[LOGINURL]',
			  '[FB]',
			  '[TW]',
			  '[SITEURL]'), array(
			  Utility::getLogo(),
			  $row->email,
			  date('Y'),
			  $core->company,
			  Url::url('/join', $data['invite_token']),
			  $core->social->facebook,
			  $core->social->twitter,
			  SITEURL), $tpl->body);

		  $msg = Swift_Message::newInstance()
				->setSubject(str_replace("[COMPANY]", $core->company, $tpl->subject))
				->setTo(array($row->email))
				->setFrom(array($core->site_email => $core->company))
				->setBody($body, 'text/html');

		  if($mailer->send($msg)) {
			  $json['type'] = 'success';
			  $json['title'] = Lang::$word->SUCCESS;
			  $json['message'] = Lang::$word->MAC_RESEND_OK;
		  } else {
			  $json['type'] = 'error';
			  $json['title'] = Lang::$word->ERROR;
			  $json['message'] = Lang::$word->SENDERROR;
			    
		  }
         print json_encode($json);
      }
	  
      /**
       * Users::updateRoleDescription()
       * 
       * @return
       */
      public static function updateRoleDescription()
      {

          $rules = array(
              'name' => array('required|string|min_len,2|max_len,60', Lang::$word->NAME),
              'description' => array('required|string|min_len,2|max_len,150', Lang::$word->DESCRIPTION),
              );

          $validate = Validator::instance();
          $safe = $validate->doValidate($_POST, $rules);
		  
		  if (empty(Message::$msgs)) {
			  $data = array(
					'name' => $safe->name, 
					'description' => $safe->description
			  );
	          
			  Db::run()->update(self::rTable, $data, array('id' => Filter::$id));
			  Message::msgModalReply(Db::run()->affected(), 'success', Lang::$word->ACC_ROLE_UPDATED, Validator::truncate($data['description'], 80));
		  } else {
			  Message::msgSingleStatus();
		  }
      }

      /**
       * Users::getAllStaff()
       * 
	   * @param int $status
	   * @param string $active
	   * @param string $is_owner
       * @return
       */
      public function getAllStaff($status = 1, $active = "y", $is_owner = false)
      {
		  $owner = ($is_owner) ? "AND type = 'owner' OR type= 'staff'" : "AND type = 'staff'";
          $sql = "
		  SELECT 
			  id,
			  username,
			  email,
			  avatar,
			  CONCAT(fname, ' ', lname) AS name 
			FROM `" . self::mTable . "` 
			WHERE status = ? 
			$owner
			AND active = ?
			ORDER BY fname;";
          $row = Db::run()->pdoQuery($sql, array($status, $active, 0))->results();

          return ($row) ? $row : 0;
      }

      /**
       * Users::getAllClients()
       * 
	   * @param int $status
	   * @param string $active
       * @return
       */
      public function getAllClients($status = 1, $active = "y")
      {
          $sql = "
		  SELECT 
			id,
			username,
			email,
			avatar,
			CONCAT(fname, ' ', lname) AS name 
		  FROM `" . self::mTable . "` 
		  WHERE status = ? 
		  AND type = ? 
		  AND active = ?
		  ORDER BY fname;";
          $row = Db::run()->pdoQuery($sql, array($status, "member", $active))->results();

          return ($row) ? $row : 0;
      }
	  
      /**
       * Users::getRoles()
       * 
       * @return
       */
      public function getRoles()
      {

          $row = Db::run()->select(self::rTable)->results();

          return ($row) ? $row : 0;

      }
	  
      /**
       * Users::getPrivileges()
       * 
       * @return
       */
      public function getPrivileges($id)
      {
          $sql = "
		  SELECT 
			rp.id,
			rp.active,
			p.id as prid,
			p.name,
			p.type,
			p.description,
			p.mode
		  FROM `" . self::rpTable . "` as rp 
			INNER JOIN `" . self::rTable . "` as r 
			  ON rp.rid = r.id 
			INNER JOIN `" . self::pTable . "` as p 
			  ON rp.pid = p.id 
		  WHERE rp.rid = ?
		  ORDER BY p.type;";

          $row = Db::run()->pdoQuery($sql, array($id))->results();

          return ($row) ? $row : 0;
      }

      /**
       * Users::activityHistoryStatus()
       * 
       * @param array $array
       * @return
       */
      public static function activityHistoryStatus($array)
      {
          switch ($array->type) {
              case "Tasks":
				  return $array->comment . ' <a href="' . Url::url("/admin/tasks", $array->task_id) . '">' .  $array->title. ' </a>';
				  break;
              case "Messages":
				  return $array->comment . ' <a href="' . Url::url("/admin/discussions/view" . $array->project_id, $array->message_id) . '">' .  $array->title. ' </a>';
				  break;
              case "Notes":
				  return $array->comment . ' <a href="' . Url::url("/admin/notes/view" . $array->project_id, $array->note_id) . '">' .  $array->title. ' </a>';
				  break;
              default:
                  return '';
				  break;
          }
      }

      /**
       * Users::activityHistoryStatusFront()
       * 
       * @param array $array
       * @return
       */
      public static function activityHistoryStatusFront($array)
      {
          switch ($array->type) {
              case "Tasks":
				  return $array->comment . ' ' .  $array->title;
				  break;
              case "Messages":
				  return $array->comment . ' ' .  $array->title;
				  break;
              case "Notes":
				  return $array->comment . ' ' .  $array->title;
				  break;
              default:
                  return '';
				  break;
          }
      }
	  
      /**
       * Users::accountLevelToTypeLabel()
       * 
       * @param mixed $level
       * @return
       */
      public static function accountLevelToTypeLabel($level)
      {
          switch ($level) {
              case 9:
                  return '<span class="wojo small inverted positive label">' . Lang::$word->OWNER . '</span>';

              case 8:
                  return '<span class="wojo small inverted primary label">' . Lang::$word->LEV8_1 . '</span>';

              case 7:
                  return '<span class="wojo small inverted secondary label">' . Lang::$word->LEV7 . '</span>';

              case 1:
                  return '<span class="wojo small inverted dark label">' . Lang::$word->LEV1 . '</span>';
          }
      }
	  
      /**
       * Users::accountLevelToType()
       * 
       * @param mixed $level
       * @return
       */
      public static function accountLevelToType($level)
      {
          switch ($level) {
              case 9:
                  return '<span class="wojo small demi positive text">' . Lang::$word->OWNER . '</span>';

              case 8:
                  return '<span class="wojo small demi primary text">' . Lang::$word->LEV8_1 . '</span>';

              case 7:
                  return '<span class="wojo small demi secondary text">' . Lang::$word->LEV7 . '</span>';

              case 1:
                  return '<span class="wojo small demi dark text">' . Lang::$word->LEV1 . '</span>';
          }
      }
  }