Source for file PolarDbQuery.class.php

Documentation is available at PolarDbQuery.class.php

  1. <?php
  2. /**
  3.  * Class to query / update database to get various data
  4.  * (day info, exercises, stats, ...)
  5.  *
  6.  * @author    Jean-Philippe Brunon <jp75018@free.fr>
  7.  * @copyright    2007-2009 Jean-Philippe Brunon
  8.  * @license    http://www.opensource.org/licenses/gpl-license.php GPL
  9.  * @package    php-endurance
  10.  * @version    $Id: PolarDbQuery.class.php 68 2009-03-28 22:57:30Z jp75018 $
  11.  */
  12.  
  13. /**
  14.  * Class to query / update database to get various data
  15.  * (day info, exercises, stats, ...)
  16.  */
  17. {
  18. /**
  19.  * Class constructor
  20.  *
  21.  * @return      void 
  22.  */
  23.   function PolarDbQuery ()
  24.   {
  25.   }
  26.  
  27. /**
  28.  * Get user information data
  29.  *
  30.  * @param    integer    $user_id User ID
  31.  * @return      array    User information (associative array with plw_user
  32.  *             SQL table structure)
  33.  */
  34.   function get_user_info($user_id)
  35.   {
  36.     $request sprintf("SELECT * FROM plw_user WHERE id = %d"$user_id);
  37.     $result mysql_query($request);
  38.     $user_info mysql_fetch_assoc($result);
  39.     mysql_free_result($result);
  40.  
  41.     return $user_info;
  42.   }
  43.  
  44. /**
  45.  * Login user, get user information data
  46.  *
  47.  * User status must be 'active'.
  48.  * Also set last visit timestamp and use user language.
  49.  *
  50.  * @param    string    $email Email of user
  51.  * @param    string    $password Password of user
  52.  * @return      array    User fields on success, else null
  53.  */
  54.   function login_user($email$password,
  55.     $email_cookie false$password_cookie false)
  56.   {
  57.     $info null;
  58.  
  59.     $request sprintf("SELECT * FROM plw_user WHERE status = 'active' AND LOWER(email) = '%s' AND password = MD5('%s')",
  60.       strtolower($email)$password);
  61.     $result mysql_query($request);
  62.     if (mysql_num_rows($result))
  63.     $info mysql_fetch_assoc($result)}
  64.     mysql_free_result($result);
  65.  
  66.   // Update last visit timestamp (do not update last mod date)
  67.     if (is_array($info))
  68.     {
  69.       $request sprintf("UPDATE plw_user SET mod_date = mod_date, visit_date = NOW() WHERE id = %d",
  70.     $info['id']);
  71.       mysql_query($request);
  72.  
  73.     // Use user language (only if a session)
  74.       if (is_array($_SESSION))
  75.       set_language($info['language'])}
  76.       $cur_time time();
  77.       setcookie('lang'$info['language']$cur_time 365 86400);
  78.       if ($email_cookie)
  79.       {
  80.       // Set email cookie
  81.     setcookie('email'$email$cur_time 365 86400);
  82.     if ($password_cookie)
  83.     {
  84.     // Set password cookie
  85.       setcookie('password'$password$cur_time 365 86400);
  86.     }
  87.     else
  88.     {
  89.     // Unset password cookie
  90.       setcookie('password'''$cur_time 1000000);
  91.     }
  92.       }
  93.       else
  94.       {
  95.       // Unset email / password cookies
  96.     setcookie('email'''$cur_time 1000000);
  97.     setcookie('password'''$cur_time 1000000);
  98.       }
  99.     }
  100.  
  101.     return $info;
  102.   }
  103.  
  104. /**
  105.  * Update user password
  106.  *
  107.  * @param    integer    $user_id User ID
  108.  * @param    string    $old_password Old (current) user password
  109.  * @param    string    $new_password New user password
  110.  * @return      boolean    true on success, else false
  111.  */
  112.   function change_user_password($user_id$old_password$new_password)
  113.   {
  114.     $ret_val false;
  115.  
  116.     $request sprintf("UPDATE plw_user SET password = MD5('%s') WHERE id = %d AND password = MD5('%s')",
  117.       $new_password$user_id$old_password);
  118.     mysql_query($request);
  119.     if (mysql_affected_rows())
  120.     $ret_val true}
  121.  
  122.     return $ret_val;
  123.   }
  124.  
  125. /**
  126.  * Create a new user (with inactive status)
  127.  *
  128.  * @param    array    $info Associative array of user fields :
  129.  *             - 'nickname' : User nickname
  130.  *             - 'email' : User email address
  131.  *             - 'password' : User password
  132.  *             - 'publish' : Publish status
  133.  * @param    integer    &$user_id ID of user created
  134.  * @param    string    &$activ_code Activation code (32 chars MD5 generated)
  135.  * @return      boolean    true on success, else false
  136.  */
  137.   function insert_user($info&$user_id&$activ_code)
  138.   {
  139.     $ret_val false;
  140.  
  141.     $activ_code md5(time('/' $email);
  142.     $request sprintf("INSERT INTO plw_user(nickname, email, cre_date, mod_date, activ_code, password, publish, language) VALUES('%s', '%s', NOW(), NOW(), '%s', MD5('%s'), '%s', '%s')",
  143.       $info['nickname']$info['email']$activ_code$info['password'],
  144.       $info['publish']$GLOBALS['lang']);
  145.     @mysql_query($request);
  146.     if (mysql_errno())
  147.     {
  148.     // Get user ID
  149.       $user_id mysql_insert_id();
  150.       $ret_val true;
  151.     }
  152.  
  153.     return $ret_val;
  154.   }
  155.  
  156. /**
  157.  * Activate a new user
  158.  *
  159.  * @param    integer    $user_id ID of user to activate
  160.  * @param    string    $activ_code Activation code (32 chars)
  161.  * @return      boolean    true on success, else false
  162.  */
  163.   function activate_user($user_id$activ_code)
  164.   {
  165.     $ret_val false;
  166.  
  167.     $request sprintf("UPDATE plw_user SET status = 'active', activ_code = NULL WHERE id = %d AND status = 'inactive' AND activ_code = '%s'",
  168.       $user_id$activ_code);
  169.     @mysql_query($request);
  170.     if ((mysql_errno()) && mysql_affected_rows())
  171.     $ret_val true}
  172.  
  173.   // Add default preferences
  174.     $this->set_user_preferences($user_id,
  175.       array('mailing_lists' => 'newsletter'));
  176.  
  177.     return $ret_val;
  178.   }
  179.  
  180. /**
  181.  * Update user fields
  182.  *
  183.  * @param    integer    $user_id User ID
  184.  * @param    array    $info Associative array of user fields :
  185.  *             - 'nickname' : User nickname
  186.  *             - 'publish' : Publish status
  187.  *             - 'language' : Language
  188.  *             - 'unit' : Unit (metric or us)
  189.  *             - 'gender' : Gender
  190.  *             - 'birthdate' : Birthdate dd/mm/yy[yy] (sep /,-,., ' ')
  191.  *             - 'height' : Height in cm (decimal sep is . or ,)
  192.  *             - 'weight' : Weight in kg (decimal sep is . or ,)
  193.  *             - 'rest_hr' : Rest HR (bpm)
  194.  *             - 'max_hr' : Max HR (bpm)
  195.  *             - 'vo2max' : VO2max in ml/kg/min (decimal sep is . or ,)
  196.  *             - 'vma' : MAS in km/h (decimal sep is . or ,)
  197.  * @return      boolean    true on success, else false
  198.  */
  199.   function update_user_info($user_id$info)
  200.   {
  201.     $ret_val false;
  202.  
  203.     if (preg_match('/^([0-9]{1,2})[\/\-\. ]([0-9]{1,2})[\/\-\. ]((19|20)?[0-9]{2})$/',
  204.       $info['birthdate']$matches))
  205.     {
  206.       $year $matches[3];
  207.       if ($year 100)
  208.       {
  209.     $year += 1900;
  210.           if ($year 1910)
  211.     $year += 100}
  212.       }
  213.       $info['birthdate'=
  214.     sprintf("%04d-%02d-%02d"$year$matches[2]$matches[1]);
  215.     }
  216.     else
  217.     $info['birthdate'null}
  218.     $info['height'strtr($info['height']',''.');
  219.     $info['weight'strtr($info['weight']',''.');
  220.     $info['vo2max'strtr($info['vo2max']',''.');
  221.     $info['vma'strtr($info['vma']',''.');
  222.     $request sprintf("UPDATE plw_user SET nickname = '%s', publish = '%s', language = '%s', unit = '%s', gender = %s, birthdate = %s, height = %s, weight = %s, rest_hr = %s, max_hr = %s, vo2max = %s, vma = %s WHERE id = %d",
  223.       $info['nickname']$info['publish']$info['language']$info['unit'],
  224.       $info['gender''\'' $info['gender''\'' 'null',
  225.       $info['birthdate''\'' $info['birthdate''\'' 'null',
  226.       $info['height'round($info['height'102'null',
  227.       $info['weight'round($info['weight'102'null',
  228.       $info['rest_hr'round($info['rest_hr']'null',
  229.       $info['max_hr'round($info['max_hr']'null',
  230.       $info['vo2max'round($info['vo2max'102'null',
  231.       $info['vma'round($info['vma'102'null',
  232.       $user_id);
  233.     @mysql_query($request);
  234.     if (mysql_errno())
  235.     {
  236.     // Use new language (only if a session)
  237.       if (is_array($_SESSION))
  238.       set_language($info['language'])}
  239.       $ret_val true;
  240.     }
  241.  
  242.     return $ret_val;
  243.   }
  244.  
  245. /**
  246.  * Get read rights on one user booknote for another user (or anonymous reader)
  247.  *
  248.  * @todo    Return day info display flag
  249.  * @todo    Add groups rights
  250.  *
  251.  * @param    integer    $publish_user_id ID of user owner of booknote
  252.  * @param    integer    $logged_user_id ID uf user logged in (null if anonymous)
  253.  * @return      string    Read rights, one of :
  254.  *             - null : <publish_user_id> does not exist
  255.  *             - 'private' : No read rights
  256.  *             - 'public' : Read rights
  257.  *             - 'public-but-desc' : Read rights except descriptions
  258.  * @param    string    &$nickname Nickname of <publish_user_id> user
  259.  */
  260.   function get_read_rights($publish_user_id$logged_user_id&$nickname)
  261.   {
  262.     $info null;
  263.     $nickname null;
  264.  
  265.     if ($publish_user_id == $logged_user_id)
  266.     {
  267.     // All rights for user on itself
  268.       $rights 'public';
  269.       if (isset($_SESSION['user_nickname']))
  270.       $nickname $_SESSION['user_nickname']}
  271.     }
  272.     else
  273.     {
  274.       $request sprintf("SELECT publish, nickname FROM plw_user WHERE id = %d",
  275.     $publish_user_id);
  276.       $result mysql_query($request);
  277.       $info mysql_fetch_assoc($result);
  278.       mysql_free_result($result);
  279.       if ($info)
  280.       {
  281.     $rights $info['publish'];
  282.     $nickname $info['nickname'];
  283.       }
  284.     }
  285.  
  286.     return $rights;
  287.   }
  288.  
  289. /**
  290.  * Get user preferences
  291.  *
  292.  * @param    integer    $user_id User ID
  293.  * @return      array    User preferences : Associative array of preferences :
  294.  *             - 'mailing_lists' : List of mailing lists
  295.  *             - 'display_width' : Browser width in pixels
  296.  *             - 'display_day_info' : Flag to display day info or not
  297.  *             - 'home_exes_sums' : To display exes stats in home page
  298.  */
  299.   function get_user_preferences($user_id)
  300.   {
  301.     $prefs array();
  302.  
  303.     $request sprintf("SELECT name, value FROM plw_user_preference WHERE user_id = %d",
  304.       $user_id);
  305.     $result mysql_query($request);
  306.     while ($row mysql_fetch_assoc($result))
  307.     $prefs[$row['name']] $row['value']}
  308.     mysql_free_result($result);
  309.  
  310.     return $prefs;
  311.   }
  312.  
  313. /**
  314.  * Set user preferences
  315.  *
  316.  * Insert preference if not exist, delete if value is '', else update value.
  317.  *
  318.  * @param    integer    $user_id User ID
  319.  * @param      array    User preferences : Associative array of preferences
  320.  *             (see get_user_preferences)
  321.  * @return      boolean    true on success, else false
  322.  */
  323.   function set_user_preferences($user_id$prefs)
  324.   {
  325.     $ret_val true;
  326.  
  327.     if (is_array($prefs))
  328.     return $ret_val}
  329.  
  330.   // 1. Get null and not null preferences
  331.     $del_prefs array();
  332.     $ins_prefs array();
  333.     reset($prefs);
  334.     while (list($name$valueeach($prefs))
  335.     {
  336.       if ($value == '')
  337.       array_push($del_prefs$name)}
  338.       else
  339.       $ins_prefs[$name$value}
  340.     }
  341.  
  342.   // 2. Delete preferences with null value
  343.     if (count($del_prefs))
  344.     {
  345.       $request sprintf("DELETE FROM plw_user_preference WHERE user_id = %d AND name IN ('%s')",
  346.     $user_idimplode('\',\''$del_prefs));
  347.       @mysql_query($request);
  348.       if (mysql_errno())
  349.       $ret_val false}
  350.     }
  351.  
  352.   // 3. Insert / update other preferences
  353.     if (count($ins_prefs))
  354.     {
  355.       reset($ins_prefs);
  356.       while (list($name$valueeach($ins_prefs))
  357.       {
  358.     $request sprintf("INSERT INTO plw_user_preference(user_id, name, value) VALUES (%d, '%s', '%s') ON DUPLICATE KEY UPDATE value = '%s'",
  359.        $user_id$namemysql_escape_string($value),
  360.        mysql_escape_string($value));
  361.     @mysql_query($request);
  362.     if (mysql_errno())
  363.     $ret_val false}
  364.       }
  365.     }
  366.  
  367.     return $ret_val;
  368.   }
  369.  
  370. /**
  371.  * Get day information data for a user
  372.  *
  373.  * @param    integer    $user_id User ID
  374.  * @param    string    $day Day (format : YYYY-MM-DD)
  375.  * @return      array    Day information (associative array with plw_day_info
  376.  *             SQL table structure)
  377.  */
  378.   function get_day_info($user_id$day)
  379.   {
  380.     $request sprintf("SELECT * FROM plw_day_info WHERE user_id = %d AND day = '%s'",
  381.       $user_id$day);
  382.     $result mysql_query($request);
  383.     $day_info mysql_fetch_assoc($result);
  384.     mysql_free_result($result);
  385.  
  386.     return $day_info;
  387.   }
  388.  
  389. /**
  390.  * Get exercise information
  391.  *
  392.  * @param    integer    $exe_id Exercise ID
  393.  * @return      array    Exercise information (associative array with
  394.  *              plw_exercise SQL table structure)
  395.  */
  396.   function get_exercise_info($exe_id)
  397.   {
  398.     $request sprintf("SELECT * FROM plw_exercise WHERE id = %d"$exe_id);
  399.     $result mysql_query($request);
  400.     $exe mysql_fetch_assoc($result);
  401.     mysql_free_result($result);
  402.  
  403.     return $exe;
  404.   }
  405.  
  406. /**
  407.  * Get exercises summary + sum / avg / max by sport within a period
  408.  * 
  409.  * Used to compute weekly statistics for instance.
  410.  *
  411.  * Consider exercises in reports only.
  412.  *
  413.  * @param    integer    $user_id User ID
  414.  * @param    string    $min_day First day in period (format : YYYY-MM-DD)
  415.  * @param    string    $max_day Last day in period (format : YYYY-MM-DD)
  416.  *             If null, then period ends at current date.
  417.  * @param    boolean    $detail true to get exercises summary, else false
  418.  * @return      array    Indexed by sport ID. For each sport :
  419.  *             - 'nb' : Number of exercises
  420.  *             - 'exe' : Array of exercises
  421.  *             - 'elapsed' : Total duration in seconds * 10
  422.  *             - 'real_distance' : Total real distance in meters
  423.  *             - 'running_index' : Average Polar running index
  424.  *             - 'max_hr' : Maximum heart rate in bpm
  425.  *             - 'max_speed' : Maximum speed rate in km/h * 10
  426.  *             - 'avg_cadence' : Average cadence in cycles / minute
  427.  *             - 'max_cadence' : Maximum cadence in cycles / minute
  428.  *             - 'ascend' : Total ascend in meters
  429.  *             - 'energy' : Total energy -Polar- in Kcal
  430.  *             - 'physio_energy' : Total physio energy -f(HR)- in Kcal
  431.  *             - 'beat_sum' : Total number of heart beats
  432.  *             For each exercise in 'exe' (if $detail = true) :
  433.  *             - 'day' : Day of exercise (format : YYYY-MM-DD)
  434.  *             - 'rank' : Rank of exercise in day
  435.  *             - 'start_time' : Start time (format : HH:MM:SS)
  436.  *             - 'elapsed' : Total duration in seconds * 10
  437.  *             - 'real_distance' : Total real distance in meters
  438.  *             - 'running_index' : Average Polar running index
  439.  *             - 'max_hr' : Maximum heart rate in bpm
  440.  *             - 'max_speed' : Maximum speed rate in km/h * 10
  441.  *             - 'avg_cadence' : Average cadence in cycles / minute
  442.  *             - 'max_cadence' : Maximum cadence in cycles / minute
  443.  *             - 'ascend' : Total ascend in meters
  444.  *             - 'energy' : Total energy -Polar- in Kcal
  445.  *             - 'physio_energy' : Total physio energy -f(HR)- in Kcal
  446.  *             - 'beat_sum' : Total number of heart beats
  447.  *             - 'exercise_type' : exe type in ('training','contest')
  448.  */
  449.   function get_exercises_by_sport($user_id$min_day$max_day null,
  450.     $detail true)
  451.   {
  452.     $exes array();
  453.  
  454.   // 1. Get sum / avg / max by sport
  455.     $request sprintf("SELECT sport_id, COUNT(*) AS nb, SUM(elapsed) AS elapsed, SUM(real_distance) AS real_distance, SUM(running_index*elapsed)/SUM(elapsed*running_index/running_index) AS running_index, MAX(max_hr) AS max_hr, MAX(max_speed) AS max_speed, SUM(avg_cadence*elapsed)/SUM(elapsed*avg_cadence/avg_cadence) AS avg_cadence, MAX(max_cadence) AS max_cadence, SUM(ascend) AS ascend, SUM(energy) AS energy, SUM(physio_energy) AS physio_energy, SUM(beat_sum) AS beat_sum FROM plw_exercise WHERE user_id = %d AND day >= '%s' AND day <= '%s' AND status = 'online' AND in_reports = 'all' GROUP BY sport_id ORDER BY sport_id",
  456.       $user_id$min_day$max_day $max_day '2099-12-31');
  457.     $result mysql_query($request);
  458.     while ($row mysql_fetch_assoc($result))
  459.     {
  460.       $exes[$row['sport_id']] $row;
  461.       unset($exes[$row['sport_id']]['sport_id']);
  462.     }
  463.     mysql_free_result($result);
  464.  
  465.   // 2. Get exercises summary
  466.     if ($detail)
  467.     {
  468.       $prev_sport_id 0;
  469.       $request sprintf("SELECT sport_id, day, rank, start_time, elapsed, real_distance, running_index, max_hr, max_speed, avg_cadence, max_cadence, ascend, energy, physio_energy, beat_sum, exercise_type FROM plw_exercise WHERE user_id = %d AND day >= '%s' AND day <= '%s' AND status = 'online' AND in_reports = 'all' ORDER BY sport_id, day, rank",
  470.     $user_id$min_day$max_day);
  471.       $result mysql_query($request);
  472.       while ($row mysql_fetch_assoc($result))
  473.       {
  474.     if ($row['sport_id'!= $prev_sport_id)
  475.     {
  476.       $prev_sport_id $row['sport_id'];
  477.       $i 0;
  478.     }
  479.     $exes[$row['sport_id']]['exe'][$i$row;
  480.     unset($exes[$row['sport_id']]['exe'][$i]['sport_id']);
  481.     $i++;
  482.       }
  483.       mysql_free_result($result);
  484.     }
  485.  
  486.     return $exes;
  487.   }
  488.  
  489. /**
  490.  * Get all laps in an exercise
  491.  *
  492.  * @param    integer    $exe_id Exercise ID
  493.  * @param    string    $lap_type Lap type in
  494.  *             ('polar','distance','altitude','interval').
  495.  *             If null, all types are returned.
  496.  * @return      array    Array of laps indexed by lap number from 1.
  497.  *             Each lap is an associative array with plw_lap
  498.  *             SQL table structure. If $lap_type is null, associative
  499.  *             array of lap types.
  500.  */
  501.   function get_exercise_laps($exe_id$lap_type null)
  502.   {
  503.     $laps array();
  504.     if ($lap_type)
  505.     $where sprintf("AND lap_type = '%s'"$lap_type)}
  506.     else
  507.     $where ''}
  508.     $request sprintf("SELECT * FROM plw_lap WHERE exercise_id = %d %s ORDER BY lap_type, rank",
  509.       $exe_id$where);
  510.     $result mysql_query($request);
  511.     while ($row mysql_fetch_assoc($result))
  512.     {
  513.       $laps[$row['lap_type']][$row['rank']] $row;
  514.       unset($laps[$row['lap_type']][$row['rank']]['exercise_id']);
  515.       unset($laps[$row['lap_type']][$row['rank']]['lap_type']);
  516.       unset($laps[$row['lap_type']][$row['rank']]['rank']);
  517.     }
  518.     mysql_free_result($result);
  519.  
  520.     if ($lap_type)
  521.     $laps $laps[$lap_type]}
  522.  
  523.     return $laps;
  524.   }
  525.  
  526. /**
  527.  * Get interval training elements in an exercise
  528.  *
  529.  * @param    integer    $exe_id Exercise ID
  530.  * @return      array    Array of interval training elements indexed from 0. Each
  531.  *             element is an associative array with plw_int_training
  532.  *             SQL table structure.
  533.  */
  534.   function get_interval_training($exe_id)
  535.   {
  536.     $elements array();
  537.     $request sprintf("SELECT * FROM plw_int_training WHERE exercise_id = %d ORDER BY rank",
  538.       $exe_id);
  539.     $result mysql_query($request);
  540.     while ($row mysql_fetch_assoc($result))
  541.     {
  542.       $elements[$row['rank']] $row;
  543.       unset($elements[$row['rank']]['exercise_id']);
  544.       unset($elements[$row['rank']]['rank']);
  545.     }
  546.     mysql_free_result($result);
  547.  
  548.     return $elements;
  549.   }
  550.  
  551. /**
  552.  * Get statistics for an exercise
  553.  *
  554.  * Statistics are for heart rate, speed, cadence, and stride length depending
  555.  * on s_mode while recording.
  556.  *
  557.  * @param    integer    $exe_id Exercise ID
  558.  * @return      array    Array of statistics indexed by type in
  559.  *             ('hr','speed','cadence','stride').
  560.  *             For each type, statistics is an array of
  561.  *             <value> => <nb of occurences in exercise>.
  562.  *             <value> is bpm for 'hr', km/h * 10 for 'speed',
  563.  *             cycles / minute for 'cadence', cm for 'stride'.
  564.  */
  565.   function get_exercise_stats($exe_id)
  566.   {
  567.     $stats array();
  568.     $request sprintf("SELECT * FROM plw_stat WHERE exercise_id = %d ORDER BY data_type, value",
  569.       $exe_id);
  570.     $result mysql_query($request);
  571.     while ($row mysql_fetch_assoc($result))
  572.     $stats[$row['data_type']][$row['value']] $row['nb']}
  573.     mysql_free_result($result);
  574.  
  575.     return $stats;
  576.   }
  577.  
  578. /**
  579.  * Get statistics for all exercises within a period
  580.  * 
  581.  * Used to compute weekly statistics for instance.
  582.  *
  583.  * Consider exercises in reports only.
  584.  *
  585.  * Statistics are for heart rate, speed, cadence, and stride length depending
  586.  * on s_mode while recording.
  587.  *
  588.  * @param    integer    $user_id User ID
  589.  * @param    string    $min_day First day in period (format : YYYY-MM-DD)
  590.  * @param    string    $max_day Last day in period (format : YYYY-MM-DD)
  591.  * @return      array    Array of statistics as in get_exercise_stats().
  592.  */
  593.   function get_stats_for_period($user_id$min_day$max_day)
  594.   {
  595.     $stats array();
  596.     $request sprintf("SELECT data_type, value, SUM(nb) AS nb FROM plw_stat s, plw_exercise e WHERE e.id = s.exercise_id AND e.user_id = %d AND e.status='online' AND e.in_reports = 'all' AND e.day >= '%s' AND e.day <= '%s' GROUP BY data_type, value ORDER BY data_type, value",
  597.       $user_id$min_day$max_day);
  598.     $result mysql_query($request);
  599.     while ($row mysql_fetch_assoc($result))
  600.     $stats[$row['data_type']][$row['value']] $row['nb']}
  601.     mysql_free_result($result);
  602.  
  603.     return $stats;
  604.   }
  605.  
  606. /**
  607.  * Get last active and public members
  608.  *
  609.  * Last means most recent members (registration date). Members are sorted
  610.  * from most recent to less recent.
  611.  *
  612.  * @param    array    $params Associative array of parameters :
  613.  *             - 'max_mbr' : Maximum number of members to return
  614.  *             - 'max_age' : Only members newer than <max_age> days
  615.  *             - 'min_exe' : Only public members with at least
  616.  *               <min_exe> public exercises are considered.
  617.  * @return      array    Array of members indexed from 0. Each member is an
  618.  *             associative array :
  619.  *             - 'user_id' : User ID
  620.  *             - 'nickname' : User nickname
  621.  *             - 'gender' : User gender in ('male','female')
  622.  *             - 'birthdate' : User birthdate (YYYY-MM-DD)
  623.  *             - 'reg_date' : registration date (YYYY-MM-DD)
  624.  *             - 'exe_nb' : Number of online exercises
  625.  */
  626.   function get_last_members_summary($params null)
  627.   {
  628.     $max_mbr $params['max_mbr'$params['max_mbr'100;
  629.     $max_age $params['max_age'$params['max_age'92;
  630.     $min_exe = isset($params['min_exe']$params['min_exe'1;
  631.     $members array();
  632.  
  633.     if ($min_exe 0)
  634.     {
  635.       $request sprintf("SELECT u.id AS user_id, u.nickname AS nickname, u.gender AS gender, u.birthdate AS birthdate, u.cre_date AS reg_date, COUNT(e.id) AS exe_nb FROM plw_user u, plw_exercise e WHERE u.id = e.user_id AND u.status = 'active' AND u.publish != 'private' AND e.status = 'online' AND DATEDIFF(NOW(),u.cre_date) <= %d GROUP BY u.id HAVING exe_nb >= %d ORDER BY reg_date DESC, user_id DESC LIMIT %d",
  636.     $max_age$min_exe$max_mbr);
  637.       $result mysql_query($request);
  638.       while ($row mysql_fetch_assoc($result))
  639.       array_push($members$row)}
  640.       mysql_free_result($result);
  641.     }
  642.     else
  643.     {
  644.     // 1. Get <max_mbr> most recent active and public members
  645.       $users array();
  646.       $user_ids array();
  647.       $request sprintf("SELECT id AS user_id, nickname, gender, birthdate, cre_date AS reg_date FROM plw_user WHERE status = 'active' AND publish != 'private' AND DATEDIFF(NOW(),cre_date) <= %d ORDER BY reg_date DESC LIMIT %d",
  648.           $max_age$max_mbr);
  649.       $result mysql_query($request);
  650.       while ($row mysql_fetch_assoc($result))
  651.       {
  652.     $users[$row['user_id']] $row;
  653.     array_push($user_ids$row['user_id']);
  654.       }
  655.       mysql_free_result($result);
  656.     // 2. Get number of exercises for those members and complete user array
  657.       if (count($user_ids))
  658.       {
  659.           $request sprintf("SELECT user_id, COUNT(*) AS exe_nb FROM plw_exercise WHERE status = 'online' AND user_id IN (%s) GROUP BY user_id",
  660.       implode(','$user_ids));
  661.     $result mysql_query($request);
  662.     while ($row mysql_fetch_assoc($result))
  663.     $users[$row['user_id']]['exe_nb'$row['exe_nb']}
  664.     mysql_free_result($result);
  665.       }
  666.     // 3. Build 0 .. N indexed array
  667.       reset($users);
  668.       while (list($user_id$usereach($users))
  669.       array_push($members$user)}
  670.     }
  671.  
  672.     return $members;
  673.   }
  674.  
  675. /**
  676.  * Get last exercises of all public (and active) users.
  677.  *
  678.  * Last means most recent exercise date / time. Exercises are sorted from most
  679.  * recent to less recent.
  680.  * Consider all online exercises having a matching sport ID (even unknown).
  681.  *
  682.  * @param    array    $params Associative array of parameters :
  683.  *             - 'max_exe' : Maximum number of exercises to return
  684.  *             - 'max_age' : Only exercises newer than <max_age> days
  685.  *             - 'min_elapsed' : Only exercises during at least
  686.  *               <min_elapsed> minutes
  687.  * @return      array    Array of exercises indexed from 0. Each exercise is an
  688.  *             associative array :
  689.  *             - 'user_id' : User ID
  690.  *             - 'nickname' : User nickname
  691.  *             - 'gender' : User gender in ('male','female')
  692.  *             - 'birthdate' : User birthdate (YYYY-MM-DD)
  693.  *             - 'weather' : Weather string
  694.  *             - 'temperature' : Temperature in Celcius x 10
  695.  *             - 'sport_index' : Sport index string
  696.  *             - 'sport_name' : Sport name in case sport is unknown
  697.  *             - 'exe_id' : Exercise ID
  698.  *             - 'exe_type' : Exercise type string
  699.  *             - 'day' : Exercise date (YYYY-MM-DD format)
  700.  *             - 'start_time' : Exercise start time (HH:MI:SS format)
  701.  *             - 'title' => Exercise title
  702.  *             - 'monitor_type' => HR Monitor ID (polar_monitors.php)
  703.  *             - 's_mode' => List of data measured (comma sep)
  704.  *             - 'elapsed' => Exercice duration in seconds x 10
  705.  *             - 'distance' => Exercice distance in meters
  706.  *             - 'ascend' => Ascend in meters
  707.  */
  708.   function get_last_exercises_summary($params null)
  709.   {
  710.     $max_exe $params['max_exe'$params['max_exe'100;
  711.     $max_age $params['max_age'$params['max_age'31;
  712.     $min_elapsed $params['min_elapsed'$params['min_elapsed'0;
  713.     $exes array();
  714.  
  715.     $request sprintf("SELECT u.id AS user_id, u.nickname AS nickname, u.gender AS gender, u.birthdate AS birthdate, d.weather AS weather, d.temperature AS temperature, s.sport_index AS sport_index, s.name AS sport_name, e.id AS exe_id, e.exercise_type AS exe_type, e.day AS day, e.start_time AS start_time, e.title AS title, e.monitor_type AS monitor_type, e.s_mode AS s_mode, e.elapsed AS elapsed, e.real_distance AS distance, e.ascend AS ascend FROM plw_user u, plw_day_info d, plw_sport s, plw_exercise e WHERE u.id = d.user_id AND u.id = s.user_id AND u.id = e.user_id AND s.id = e.sport_id AND d.day = e.day AND u.status = 'active' AND u.publish != 'private' AND e.status = 'online' AND DATEDIFF(NOW(),d.day) <= %d AND e.elapsed >= %d ORDER BY day DESC, start_time DESC, user_id LIMIT %d",
  716.       $max_age$min_elapsed 600$max_exe);
  717.     $result mysql_query($request);
  718.     while ($row mysql_fetch_assoc($result))
  719.     array_push($exes$row)}
  720.     mysql_free_result($result);
  721.  
  722.     return $exes;
  723.   }
  724.  
  725. /**
  726.  * Get global statistics about active members / online exercises
  727.  *
  728.  * Consider all active members.
  729.  * Consider all online exercises (even with none matching sport ID)
  730.  *
  731.  * @param    array    $params Associative array of parameters :
  732.  *             - 'publish_list' : Array of publish status to filter
  733.  *               ('public' => 'public' or 'public-but-desc')
  734.  *             - 'by_publish' : Split by publish status if true
  735.  * @return      array    Associative arrays of records :
  736.  *             + 'mbr' : active member count indexed by
  737.  *             publish status ('all' if not splitted), 'public' and
  738.  *             'public-but-desc' are grouped as 'public'.
  739.  *             Each record is an associative array :
  740.  *             - 'nb' => Number of active members
  741.  *             + 'exe' : Exercise count indexed by
  742.  *             publish status ('all' if not splitted), 'public' and
  743.  *             'public-but-desc' are grouped as 'public'.
  744.  *             Each record is an associative array :
  745.  *             - 'nb' => Number of exercises
  746.  *             - 'elapsed' => Sum of exercices duration in seconds x 10
  747.  *             Both arrays are sorted by publish status;
  748.  */
  749.   function get_global_stats($params)
  750.   {
  751.     $where array();
  752.     $order_by array();
  753.     $group_by array();
  754.     $group_by_col array();
  755.     if (is_array($params['publish_list']))
  756.     {
  757.       if (in_array('public'$params['publish_list']))
  758.       array_push($params['publish_list']'public-but-desc')}
  759.       array_push($wheresprintf("u.publish IN ('%s')",
  760.     implode('\',\''$params['publish_list'])));
  761.     }
  762.     if ($params['by_publish'])
  763.     {
  764.       array_push($group_by_col,
  765.     'IF(u.publish=\'private\', \'private\', \'public\') AS my_publish');
  766.       array_push($group_by'my_publish');
  767.       array_push($order_by'my_publish');
  768.     }
  769.     $stats array();
  770.  
  771.     $request sprintf("SELECT %sCOUNT(*) AS nb FROM plw_user u WHERE u.status = 'active' %s%s%s",
  772.       count($group_by_colimplode(', '$group_by_col', ' '',
  773.       count($where' AND ' implode(' AND '$where'',
  774.       count($group_by' GROUP BY ' implode(', '$group_by'',
  775.       count($order_by' ORDER BY ' implode(', '$order_by'');
  776.     $result mysql_query($request);
  777.     while ($row mysql_fetch_assoc($result))
  778.     {
  779.       $key_publish $row['my_publish'$row['my_publish''all';
  780.       if ($row['my_publish'])
  781.       unset($row['my_publish'])}
  782.       $stats['mbr'][$key_publish$row;
  783.     }
  784.     mysql_free_result($result);
  785.  
  786.     $request sprintf("SELECT %sCOUNT(*) AS nb, SUM(e.elapsed) AS elapsed FROM plw_user u, plw_exercise e WHERE u.id = e.user_id AND u.status = 'active' AND e.status = 'online'%s%s%s",
  787.       count($group_by_colimplode(', '$group_by_col', ' '',
  788.       count($where' AND ' implode(' AND '$where'',
  789.       count($group_by' GROUP BY ' implode(', '$group_by'',
  790.       count($order_by' ORDER BY ' implode(', '$order_by'');
  791.     $result mysql_query($request);
  792.     while ($row mysql_fetch_assoc($result))
  793.     {
  794.       $key_publish $row['my_publish'$row['my_publish''all';
  795.       if ($row['my_publish'])
  796.       unset($row['my_publish'])}
  797.       $stats['exe'][$key_publish$row;
  798.     }
  799.     mysql_free_result($result);
  800.  
  801.     return $stats;
  802.   }
  803.  
  804. /**
  805.  * Get global statistics about online exercises
  806.  *
  807.  * Consider all active members.
  808.  * Consider all online exercises having a matching sport ID (even unknown).
  809.  *
  810.  * @param    array    $params Associative array of parameters :
  811.  *             - 'max_age' : Only exercises newer than <max_age> days
  812.  *             - 'min_elapsed' : Only exercises during at least
  813.  *               <min_elapsed> minutes
  814.  *             - 'publish_list' : Array of publish status to filter
  815.  *               ('public' => 'public' or 'public-but-desc')
  816.  *             - 'by_publish' : Split by publish status if true
  817.  *             - 'sport_list' : Array of sport indexes to filter
  818.  *             - 'by_sport' : Split by sport index if true
  819.  * @param    integer    &$sum_nb_exe Total nb of matching exercises
  820.  * @return      array    Associative array of records indexed by
  821.  *             publish status ('all' if not splitted), 'public' and
  822.  *             'public-but-desc' are grouped as 'public'.
  823.  *             then by sport index ('all' if not splitted).
  824.  *             Each record is an associative array :
  825.  *             - 'nb' => Number of exercises
  826.  *             - 'elapsed' => Sum of exercices duration in seconds x 10
  827.  *             - 'distance' => Sum of exercices distance in meters
  828.  *             - 'ascend' => Sum of exercices ascend in meters
  829.  *             Array is sorted by publish status, then by decreasing
  830.  *             number of exercises for each sport.
  831.  */
  832.   function get_exercises_stats($params&$sum_nb_exe)
  833.   {
  834.     $sum_nb_exe 0;
  835.     $max_age $params['max_age'$params['max_age'99999;
  836.     $min_elapsed $params['min_elapsed'$params['min_elapsed'0;
  837.     $where array();
  838.     $order_by array();
  839.     $group_by array();
  840.     $group_by_col array();
  841.     if (is_array($params['publish_list']))
  842.     {
  843.       if (in_array('public'$params['publish_list']))
  844.       array_push($params['publish_list']'public-but-desc')}
  845.       array_push($wheresprintf("u.publish IN ('%s')",
  846.     implode('\',\''$params['publish_list'])));
  847.     }
  848.     if ($params['by_publish'])
  849.     {
  850.       array_push($group_by_col,
  851.     'IF(u.publish=\'private\', \'private\', \'public\') AS my_publish');
  852.       array_push($group_by'my_publish');
  853.       array_push($order_by'my_publish');
  854.     }
  855.     if (is_array($params['sport_list']))
  856.     {
  857.       array_push($wheresprintf("s.sport_index IN ('%s')",
  858.     implode('\',\''$params['sport_list'])));
  859.     }
  860.     if ($params['by_sport'])
  861.     {
  862.       array_push($group_by_col's.sport_index AS my_sport_index');
  863.       array_push($group_by'my_sport_index');
  864.       array_push($order_by'nb DESC, s.sport_index');
  865.     }
  866.     $stats array();
  867.  
  868.     $request sprintf("SELECT %sCOUNT(*) AS nb, SUM(e.elapsed) AS elapsed, SUM(e.real_distance) AS distance, SUM(e.ascend) AS ascend FROM plw_user u, plw_sport s, plw_exercise e WHERE u.id = s.user_id AND u.id = e.user_id AND s.id = e.sport_id AND u.status = 'active' AND e.status = 'online' AND DATEDIFF(NOW(),e.day) <= %d AND e.elapsed >= %d%s%s%s",
  869.       count($group_by_colimplode(', '$group_by_col', ' '',
  870.       $max_age$min_elapsed 600,
  871.       count($where' AND ' implode(' AND '$where'',
  872.       count($group_by' GROUP BY ' implode(', '$group_by'',
  873.       count($order_by' ORDER BY ' implode(', '$order_by'');
  874.     $result mysql_query($request);
  875.     while ($row mysql_fetch_assoc($result))
  876.     {
  877.       $key_publish $row['my_publish'$row['my_publish''all';
  878.       if ($row['my_publish'])
  879.       unset($row['my_publish'])}
  880.       $key_sport $row['my_sport_index'$row['my_sport_index''all';
  881.       if ($row['my_sport_index'])
  882.       unset($row['my_sport_index'])}
  883.       $stats[$key_publish][$key_sport$row;
  884.       $sum_nb_exe += $row['nb'];
  885.     }
  886.     mysql_free_result($result);
  887.  
  888.     return $stats;
  889.   }
  890.  
  891. /**
  892.  * Delete day info from database (by user ID and day)
  893.  * 
  894.  * @param    integer    $user_id User ID
  895.  * @param    string    $day day of day info (format : YYYY-MM-DD)
  896.  * @return      boolean    true on success, else false (no day info)
  897.  */
  898.   function delete_day_info($user_id$day)
  899.   {
  900.     mysql_query("DELETE FROM plw_day_info WHERE user_id = $user_id AND day = '$day'");
  901.     $ret_val mysql_affected_rows(true false;
  902.  
  903.     return $ret_val;
  904.   }
  905.  
  906. /**
  907.  * Delete exercise and all related data from database by user ID, day, and rank
  908.  * 
  909.  * Note : Get exercise ID, then calls delete_exercise_by_id().
  910.  *
  911.  * @param    integer    $user_id User ID
  912.  * @param    string    $day day of exercise (format : YYYY-MM-DD)
  913.  * @param    integer    $rank Rank of exercise within day
  914.  * @return      boolean    true on success, else false (no exercise)
  915.  */
  916.   function delete_exercise_by_day_rank($user_id$day$rank)
  917.   {
  918.     $request sprintf("SELECT id FROM plw_exercise WHERE user_id = %d AND day = '%s' AND rank = %d",
  919.       $user_id$day$rank);
  920.     $result mysql_query($request);
  921.     if ($row mysql_fetch_assoc($result))
  922.     $ret_val $this->delete_exercise_by_id($row['id'])}
  923.     else
  924.     $ret_val false}
  925.     mysql_free_result($result);
  926.  
  927.     return $ret_val;
  928.   }
  929.  
  930. /**
  931.  * Delete exercise and all related data from database by exercise ID
  932.  * 
  933.  * Note : Related data in tables :
  934.  * - plw_data : Exercise data as in HRM file (if recorded)
  935.  * - plw_stat : Exercise statistics (if recorded)
  936.  * - plw_int_training : Interval training elements (if type is int_training)
  937.  * - plw_lap : Exercise laps
  938.  *
  939.  * @param    integer    $id Exercise ID
  940.  * @return      boolean    true on success, else false (no exercise)
  941.  */
  942.   function delete_exercise_by_id($id)
  943.   {
  944.     mysql_query("DELETE FROM plw_data WHERE exercise_id = $id");
  945.     mysql_query("DELETE FROM plw_stat WHERE exercise_id = $id");
  946.     mysql_query("DELETE FROM plw_int_training WHERE exercise_id = $id");
  947.     mysql_query("DELETE FROM plw_lap WHERE exercise_id = $id");
  948.  
  949.     mysql_query("DELETE FROM plw_exercise WHERE id = $id");
  950.     $ret_val mysql_affected_rows(true false;
  951.  
  952.     return $ret_val;
  953.   }
  954. }
  955. ?>

Documentation generated on Sat, 28 Mar 2009 23:16:08 +0000 by phpDocumentor 1.4.1