Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/site/app/controllers/components/newsfeed.php
blob: ffdacdc6f855df2c7039d216fc90b168ccc4dc11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is addons.mozilla.org site.
 *
 * The Initial Developer of the Original Code is
 * The Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Justin Scott <fligtar@mozilla.com> (Original Author)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
class NewsfeedComponent extends Object {
    var $controller;
    
   /**
    * Save a reference to the controller on startup
    * @param object &$controller the controller using this component
    */
    function startup(&$controller) {
        $this->controller =& $controller;
    }
    
   /**
    * Generates add-on newsfeed for user
    */
    function generate($fbUser, $friends, $favorites, $days = 7) {
        $newsfeed = array();
        
        $newVersionsOfFavorites = $this->_getNewVersionsOfFavorites($favorites, $days);
        $friendFavoriteUpdates = $this->_getFriendFavoriteUpdates($friends, $days);
        $f_recommendations = $this->_getFriendRecommendations($friends, $favorites);
        $newUsers = $this->_getNewFriendUsers($friends, $days);
        //$s_recommendations = $this->_getSimilarRecommendations($fbUser, $favorites);
        
        // Include up to 2 new user stories
        $newsfeed = array_merge($newsfeed, $this->_pullStories($newUsers, 2));
        
        // Include up to 2 new version stories
        $newsfeed = array_merge($newsfeed, $this->_pullStories($newVersionsOfFavorites, 2));
        
        // Include 1 friend recommendation
        $newsfeed = array_merge($newsfeed, $this->_pullStories($f_recommendations, 1));
        
        // Fill the rest with favorite updates
        $newsfeed = array_merge($newsfeed, $this->_pullStories($friendFavoriteUpdates, (10 - count($newsfeed))));
        
        // randomize stories
        shuffle($newsfeed);
        
        return $newsfeed;
    }
    
    function _pullStories($stories, $number) {
        // If no stories, return none
        if (empty($stories)) {
            return array();
        }
        
        // If more stories requested than available, return all stories
        if (count($stories) < $number) {
            return $stories;
        }
        
        // Otherwise, pull the appropriate number of stories randomly
        $newsfeed = array();
        $rand = array_rand($stories, $number);
        if (is_array($rand)) {
            foreach ($rand as $key) {
                $newsfeed[] = $stories[$key];
            }
        }
        else {
            $newsfeed[] = $stories[$rand];
        }
        
        return $newsfeed;        
    }
    
   /**
    * Gets stories for any new versions of the user's favorite add-ons
    */
    function _getNewVersionsOfFavorites($favorites, $days) {
        // If no favorites, return
        if (empty($favorites))
            return array();
        
        $stories = array();
        
        $favorites_string = implode(',', $favorites);
        
        $results = $this->controller->Addon->query("
                SELECT
                    addons.id,
                    versions.version,
                    files.datestatuschanged,
                    translations.localized_string AS name
                FROM addons
                INNER JOIN versions ON addons.id=versions.addon_id
                INNER JOIN files ON versions.id=files.version_id
                INNER JOIN translations ON addons.name=translations.id
                WHERE
                    addons.id IN ({$favorites_string}) AND
                    files.status = 4 AND
                    translations.locale = 'en-US' AND
                    files.datestatuschanged >= DATE_SUB(NOW(), INTERVAL {$days} DAY)
                GROUP BY addons.id
                ORDER BY files.datestatuschanged DESC
            ", true);
        
        if (!empty($results)) {
            foreach ($results as $result) {
                $stories[] = array(
                    'type' => 'story',
                    'icon' => 'newversion.png',
                    'story' => 'Version '.$result['versions']['version'].' of <a href="'.FB_URL.'/view/'.$result['addons']['id'].'?ref=afnv">'.$result['translations']['name'].'</a> is now available.',
                    'timestamp' => $result['files']['datestatuschanged']
                    );
            }
        }
        
        return $stories;
    }

   /**
    * Gets friends that recently added the app
    */
    function _getNewFriendUsers($friends, $days) {
        // If no friends, return
        if (empty($friends))
            return array();
        
        $stories = array();
        
        $results = $this->controller->FacebookFavorite->query("
                SELECT
                    fb_user
                FROM facebook_users
                WHERE
                    added >= DATE_SUB(NOW(), INTERVAL {$days} DAY) AND
                    fb_user IN ({$friends}) AND
                    removed = '0000-00-00 00:00:00'
                ORDER BY added DESC
                LIMIT 5                
            ", true);
        
        if (!empty($results)) {
            foreach ($results as $result) {
                $stories[] = array(
                    'type' => 'story',
                    'icon' => 'addedfavorite.png',
                    'story' => '<a href="'.FB_URL.'/favorites/user/'.$result['facebook_users']['fb_user'].'"><fb:name uid="'.$result['facebook_users']['fb_user'].'" linked="false" shownetwork="false" /></a>  added the Rock Your Firefox application.'
                    );
            }
        }
        
        return $stories;
    }
    
   /**
    * Gets updates for any friend activity
    */
    function _getFriendFavoriteUpdates($friends, $days) {
        // If no friends, return
        if (empty($friends))
            return array();
        
        $stories = array();
        
        $results = $this->controller->FacebookFavorite->query("
                SELECT
                    addons.id,
                    GROUP_CONCAT(facebook_favorites.fb_user) AS friends,
                    facebook_favorites.created,
                    translations.localized_string AS name
                FROM facebook_favorites
                INNER JOIN addons ON facebook_favorites.addon_id=addons.id
                INNER JOIN translations ON translations.id=addons.name
                WHERE
                    facebook_favorites.created >= DATE_SUB(NOW(), INTERVAL {$days} DAY) AND
                    translations.locale = 'en-US' AND
                    facebook_favorites.fb_user IN ({$friends})
                GROUP BY addons.id
                ORDER BY facebook_favorites.created DESC
                LIMIT 5                
            ", true);
        
        if (!empty($results)) {
            foreach ($results as $result) {
                $ffriends = explode(',', $result[0]['friends']);
                if (count($ffriends) == 1) {
                    $possessive = '<fb:pronoun uid="'.$ffriends[0].'" possessive="true" />';
                    $names = '<a href="'.FB_URL.'/favorites/user/'.$ffriends[0].'"><fb:name uid="'.$ffriends[0].'" linked="false" /></a>';
                }
                else {
                    $possessive = 'their';
                    if (count($ffriends) == 2) {
                        $names = '<a href="'.FB_URL.'/favorites/user/'.$ffriends[0].'"><fb:name uid="'.$ffriends[0].'" linked="false" /></a>';
                        $names .= ' and <a href="'.FB_URL.'/favorites/user/'.$ffriends[1].'"><fb:name uid="'.$ffriends[1].'" linked="false" /></a>';
                    }
                    else {
                        $names = '<a href="'.FB_URL.'/favorites/addon/'.$result['addons']['id'].'">'.count($ffriends).' friends</a>';
                    }
                }
                
                $stories[] = array(
                    'type' => 'story',
                    'icon' => 'addedfavorite.png',
                    'story' => $names.' added <a href="'.FB_URL.'/view/'.$result['addons']['id'].'?ref=aff">'.$result['translations']['name'].'</a> to '.$possessive.' favorite add-ons.',
                    'timestamp' => $result['facebook_favorites']['created']
                    );
            }
        }
        
        return $stories;
    }
    
   /**
    * Tries to recommend add-ons based on friends' favorites
    */
    function _getFriendRecommendations($friends, $favorites) {
        // If no friends, return
        if (empty($friends))
            return array();
        
        $stories = array();
        $favorites_string = implode(',', $favorites);
        
        $results = $this->controller->FacebookFavorite->query("
                    SELECT
                        addons.id,
                        COUNT(*) AS favorited,
                        translations_n.localized_string AS name,
                        translations_s.localized_string AS summary,
                        (SELECT COUNT(*) FROM previews WHERE previews.addon_id=addons.id) AS pcount
                    FROM facebook_favorites
                    INNER JOIN addons ON facebook_favorites.addon_id=addons.id
                    INNER JOIN translations AS translations_n ON translations_n.id=addons.name
                    INNER JOIN translations AS translations_s ON translations_s.id=addons.summary
                    WHERE
                        translations_n.locale = 'en-US' AND
                        translations_s.locale = 'en-US' AND
                        facebook_favorites.fb_user IN ({$friends}) AND
                        ".(!empty($favorites_string) ? "addons.id NOT IN ({$favorites_string}) AND" : "")."
                        addons.inactive = 0 AND
                        addons.status = ".STATUS_PUBLIC."
                    GROUP BY addons.id
                    ORDER BY favorited DESC
                    LIMIT 5
                    ", true);
        
        if (!empty($results)) {
            foreach ($results as $result) {
                if ($result[0]['favorited'] > 1) {
                    $stories[] = array(
                        'type' => 'fullstory',
                        'icon' => 'recommendation.png',
                        'story' => '<span class="title">Recommendation:</span> <a href="'.FB_URL.'/favorites/addon/'.$result['addons']['id'].'?ref=affr">'.$result[0]['favorited'].' of your friends</a> like <a href="'.FB_URL.'/view/'.$result['addons']['id'].'">'.$result['translations_n']['name'].'</a>. Have you tried it?',
                        'body' => $this->controller->_trimSummary($result['translations_s']['summary'], 200),
                        'image' => ($result[0]['pcount'] > 0 ? FB_IMAGE_SITE.'/images/addon_preview/'.$result['addons']['id'].'/1' : ''),
                        'image_url' => FB_URL.'/view/'.$result['addons']['id'].'?ref=affri'
                        );
                }
            }
        }
        
        return $stories;
    }
    
   /**
    * Tries to recommend add-ons based on similar users' favorites
    * As in, "people who had these add-ons favorited also liked ____"
    */
    /*function _getSimilarRecommendations($fbUser, $favorites) {
        // If no favorites, return
        if (empty($favorites))
            return array();
        
        $stories = array();
        $favorites_string = implode(',', $favorites);
        
        // Get top 2 favorited add-ons that user has favorited
        $top2 = $this->controller->FacebookFavorite->query("
                    SELECT
                        addon_id,
                        COUNT(*) AS favorited
                    FROM facebook_favorites
                    WHERE
                        addon_id IN ({$favorites_string})
                    GROUP BY addon_id
                    ORDER BY favorited DESC
                    LIMIT 2
                    ", true);
        
        pr($top2);
        
        // Find other users who have favorited all 2
        $similarUsers = $this->controller->FacebookFavorite->query("
                    SELECT
                        fb.fb_user
                    FROM facebook_favorites AS fb
                    LEFT JOIN facebook_favorites AS addon1 ON addon1.fb_user=fb.fb_user
                    LEFT JOIN facebook_favorites AS addon2 ON addon2.fb_user=fb.fb_user
                    WHERE
                        addon1.addon_id = {$top2[0]['facebook_favorites']['addon_id']} AND
                        addon2.addon_id = {$top2[1]['facebook_favorites']['addon_id']}
                    GROUP BY fb.fb_user
                    ", true);
        
        pr($similarUsers);

        if (!empty($results)) {
            foreach ($results as $result) {
                $stories[] = array(
                    'icon' => 'favorite_recommend.png',
                    'story' => '<b>Recommendation:</b> <a href="'.FB_URL.'/favorites/addon/'.$result['addons']['id'].'">'.$result[0]['favorited'].'</a> of your friends like <a href="'.FB_URL.'/view/'.$result['addons']['id'].'">'.$result['translations']['name'].'</a>. Have you tried it?',
                    'timestamp' => 0
                    );
            }
        }
        
        return $stories;
    }*/
    
   /**
    * Counts new add-ons since last favorite added
    */
    function getNewAddonCount($fbUser) {        
        // Get date of last added favorite
        $lastadded = $this->controller->FacebookFavorite->query("
                        SELECT
                            facebook_favorites.created
                        FROM facebook_favorites
                        WHERE
                            facebook_favorites.fb_user = '{$fbUser}'
                        ORDER BY facebook_favorites.created DESC
                        LIMIT 1
                    ");
        
        if (!empty($lastadded)) {
            $daysSince = (time() - strtotime($lastadded[0]['facebook_favorites']['created'])) / 86400;
            
            if (!empty($lastadded) && $daysSince >= 14) {
                // Get count of add-ons added after last favorite
                $count = $this->controller->Addon->query("
                            SELECT
                                COUNT(*) as num
                            FROM addons
                            WHERE
                                created > '{$lastadded[0]['facebook_favorites']['created']}'
                            ", true);
                    
                return 'There are '.$count[0][0]['num'].' new add-ons since you last added a favorite. <a href="'.FB_URL.'/browse?ref=afsb">Find your next favorite!</a>';
            }
        }
        
        return '';
    }
}
?>