40e0bf6dd51a4522b744b43f16404564d5c77346
[atutor.git] / mods / photos / include / classes / PhotoAlbum.class.php
1 <?php
2 /***********************************************************************/
3 /* ATutor                                                                                                                          */
4 /***********************************************************************/
5 /* Copyright (c) 2002-2009                                                                                         */
6 /* Adaptive Technology Resource Centre / Inclusive Design Institution  */
7 /* http://atutor.ca                                                                                                        */
8 /*                                                                                                                                         */
9 /* This program is free software. You can redistribute it and/or           */
10 /* modify it under the terms of the GNU General Public License             */
11 /* as published by the Free Software Foundation.                                           */
12 /***********************************************************************/
13 // $Id$
14
15 /** 
16   * Photo Album
17   * Note: Using intval for photo id, if the system is large enough, int might run out of bound.
18   */
19 class PhotoAlbum {
20         var $id;
21
22         /** Constructor */
23         function PhotoAlbum($id=0){
24                 $this->id = intval($id);
25         }
26
27         /** */
28         function addPhoto($name, $comment, $member_id){
29                 global $db, $addslashes;
30                 $name           = $addslashes($name);
31                 $comment        = $addslashes($comment);
32                 $member_id      = intval($member_id);
33                 $album_id       = $this->id;
34
35                 //get max order
36                 $sql = 'SELECT MAX(ordering) AS ordering FROM '.TABLE_PREFIX."pa_photos WHERE album_id=$album_id";
37                 $result = mysql_query($sql, $db);
38                 if ($result){
39                         $row = mysql_fetch_assoc($result);
40                         $ordering = intval($row['ordering']) + 1;
41                 } else {
42                         $ordering = 1;
43                 }
44                 
45                 $sql = "INSERT INTO ".TABLE_PREFIX."pa_photos (name, description, member_id, album_id, ordering, created_date, last_updated) VALUES ('$name', '$comment', $member_id, $album_id, $ordering, NOW(), NOW())";
46                 $result = mysql_query($sql, $db);
47                 return $result;
48         }
49
50         /** */
51         function getPhotoInfo($id){
52                 global $db, $addslashes;
53                 $id = intval($id);
54                 $row = array();
55
56                 $sql = "SELECT * FROM ".TABLE_PREFIX."pa_photos WHERE id=$id";
57                 $result = mysql_query($sql, $db);
58                 if ($result){
59                         $row = mysql_fetch_assoc($result);
60                 } else {
61                         return false;
62                 }
63                 return $row;
64         }
65
66         /** 
67          * Edit the info of the photo.  (just description for now)
68          * @param       int             photo id
69          * @param       string  the caption of the photo
70          * @param       string  alternative text of the image.
71          */
72         function editPhoto($id, $description, $alt_text){
73                 global $db, $addslashes;
74                 $id = intval($id);
75                 $description = $addslashes($description);
76                 $alt_text = $addslashes($alt_text);
77
78                 $sql = "UPDATE ".TABLE_PREFIX."pa_photos SET description='$description', alt_text='$alt_text', last_updated=NOW() WHERE id=$id";
79                 $result = mysql_query($sql);
80                 return $result;
81         }
82
83         /** 
84          * Edit the order of the photo.  
85          * @param       int             photo id
86          * @param       int             the ordering of this photo within this album
87          */
88         function editPhotoOrder($id, $ordering){
89                 global $db, $addslashes;
90                 $id = intval($id);
91                 $ordering = intval($ordering);
92
93                 $sql = "UPDATE ".TABLE_PREFIX."pa_photos SET ordering=$ordering, last_updated=NOW() WHERE id=$id";
94                 $result = mysql_query($sql);
95                 return $result;
96         }
97
98         /** 
99          * Delete photo
100          * @param       int             photo id
101          */
102         function deletePhoto($id){
103                 global $db;
104                 $id = intval($id);
105                 //delete photo file
106                 $sql = 'SELECT a.id AS aid, p.name AS name, p.ordering AS ordering, a.created_date AS album_date, p.created_date AS photo_date FROM '.TABLE_PREFIX.'pa_photos p, '.TABLE_PREFIX."pa_albums a WHERE a.id=p.album_id AND p.id=$id";
107                 $result = mysql_query($sql, $db);
108                 if ($result){
109                         $row = mysql_fetch_assoc($result);
110                 }
111                 //if the aid don't match each other, there must be something wrong.
112                 if($row['aid']!=$this->id){
113                         return false;                   
114                 }
115                 $albumpath = AT_PA_CONTENT_DIR.getAlbumFilePath($row['aid'], $row['album_date']);
116                 $filepath = $albumpath.DIRECTORY_SEPARATOR.getPhotoFilePath($id, $row['name'], $row['photo_date']);     //orig
117                 $filepath_tn = $albumpath.'_tn'.DIRECTORY_SEPARATOR.getPhotoFilePath($id, $row['name'], $row['photo_date']); //thumbnail
118                 if (is_file($filepath) && is_file($filepath_tn)){
119                         unlink($filepath);
120                         unlink($filepath_tn);
121                 }
122                 
123                 //delete photo comments
124                 $sql = 'DELETE FROM '.TABLE_PREFIX."pa_photo_comments WHERE photo_id=$id";
125                 mysql_query($sql, $db);
126
127                 //reorder images
128                 $sql = 'UPDATE '.TABLE_PREFIX.'pa_photos SET `ordering`=`ordering`-1 WHERE album_id='.$row['aid'].' AND `ordering` > '.$row['ordering'];
129                 mysql_query($sql, $db);
130
131                 //delete the photo from db
132                 $sql = "DELETE FROM ".TABLE_PREFIX."pa_photos WHERE id=$id";
133                 mysql_query($sql, $db);
134                 
135                 return true;
136         }
137
138         /** 
139          * Create an album
140          * @param       string          name of the album
141          * @param       string          location of where this album took place
142          * @param       string          descriptive text of this album
143          * @param       int                     check include/constants.inc.php
144          * @param       int                     permission, 0 for private, 1 for shared
145          * @param       int                     album author
146          * @param       int                     OPTIONAL, Photo cover for this album
147          */
148         function createAlbum($name, $location, $description, $type, $permission, $member_id, $photo_id=0){
149                 global $addslashes, $db;
150
151                 //handle input
152                 $name           = $addslashes($name);
153                 $locatoin       = $addslashes($location);
154                 $description = $addslashes($description);
155                 $type           = intval($type);
156                 $type           = ($type<=0)?AT_PA_TYPE_MY_ALBUM:$type;
157                 $permission     = intval($permission);
158                 $member_id  = intval($member_id);
159                 $photo_id       = intval($photo_id);
160
161                 $sql = "INSERT INTO ".TABLE_PREFIX."pa_albums (name, location, description, type_id, member_id, permission, photo_id, created_date, last_updated) VALUES ('$name', '$location', '$description', $type, $member_id, $permission, $photo_id, NOW(), NOW())";
162                 $result = mysql_query($sql, $db);
163
164                 //if course album, add a record.
165                 if ($type==AT_PA_TYPE_COURSE_ALBUM){
166                         $aid = mysql_insert_id();
167                         $sql = "INSERT INTO ".TABLE_PREFIX."pa_course_album (course_id, album_id) VALUES ($_SESSION[course_id], $aid)";
168                         $result = mysql_query($sql, $db);
169                 }
170                 return $result;
171         }
172
173         /** 
174          * Updating album cover.
175          * @param       int             photo id (the album cover)       
176          * @precondition        user has the ability to edit the album.
177          */
178         function editAlbumCover($pid){
179                 global $db;
180
181                 //safe guard
182                 $pid = intval($pid);
183                 $aid = $this->id;
184
185                 //pid and aid cannot be empty
186                 if ($pid<=0 || $aid<=0){
187                         return false;
188                 }
189                 
190                 $sql = "UPDATE ".TABLE_PREFIX."pa_albums SET photo_id=$pid WHERE id=$aid";
191                 $result = mysql_query($sql, $db);
192                 return $result;
193         }
194         
195         /** 
196          * Update album
197          * @param       string          name of the album
198          * @param       string          location of where this album took place
199          * @param       string          descriptive text of this album
200          * @param       int                     check include/constants.inc.php
201          * @param       int                     permission, 0 for private, 1 for shared
202          */
203         function editAlbum($name, $location, $description, $type, $permission){
204                 global $db, $addslashes;
205                 $id                      = $this->id;
206                 $name            = $addslashes($name);
207                 $location        = $addslashes($location);
208                 $description = $addslashes($description);
209                 $type            = ($type==AT_PA_TYPE_COURSE_ALBUM)?AT_PA_TYPE_COURSE_ALBUM:AT_PA_TYPE_MY_ALBUM;
210                 $permission      = ($permission==AT_PA_SHARED_ALBUM)?AT_PA_SHARED_ALBUM:AT_PA_PRIVATE_ALBUM;
211                 $info            = $this->getAlbuminfo();
212
213                 //if type has been changed, run the query to update the course_album table
214                 if ($info['type_id'] != $type){
215                         //if course album, add a record.                
216                         if ($type==AT_PA_TYPE_COURSE_ALBUM){
217                                 $sql = "INSERT INTO ".TABLE_PREFIX."pa_course_album (course_id, album_id) VALUES ($_SESSION[course_id], $id)";
218                                 $result = mysql_query($sql, $db);
219                         } else {
220                                 $sql = 'DELETE FROM '.TABLE_PREFIX."pa_course_album WHERE course_id=$_SESSION[course_id] AND album_id=$id";
221                                 $result = mysql_query($sql, $db);
222                         }
223                 }
224
225                 $sql = 'UPDATE '.TABLE_PREFIX."pa_albums SET name='$name', location='$location', description='$description', type_id=$type, permission=$permission WHERE id=$id";
226                 $result = mysql_query($sql, $db);
227                 return $result;
228         }
229
230         /** 
231          * Delete an album and all associations
232          */
233         function deleteAlbum(){
234                 //TODO Error checking on each step, if anyone fails, should report it to user
235                 global $db;
236                 $id = $this->id;
237
238                 //clean directory               
239                 $sql = 'SELECT created_date FROM '.TABLE_PREFIX."pa_albums WHERE id=$id";
240                 $result = mysql_query($sql, $db);
241                 if ($result){
242                         $row = mysql_fetch_assoc($result);
243                 }
244                 $filepath = AT_PA_CONTENT_DIR . getAlbumFilePath($id, $row['created_date']);    //orig
245                 $filepath_tn = $filepath.'_tn'; //thumbnails
246                 //delete files
247                 if (is_dir($filepath) && is_dir($filepath_tn)){
248                         clr_dir($filepath);
249                         clr_dir($filepath_tn);
250                 }
251
252                 //delete all photo comments
253                 $sql = 'DELETE c.* FROM '.TABLE_PREFIX.'pa_photo_comments c LEFT JOIN '.TABLE_PREFIX."pa_photos p ON c.photo_id=p.id WHERE p.album_id=$id";
254                 mysql_query($sql, $db);
255
256                 //delete all photos within this album
257                 $sql = "DELETE FROM ".TABLE_PREFIX."pa_photos WHERE album_id=$id";
258                 mysql_query($sql, $db);
259
260                 //delete all album comments
261                 $sql = 'DELETE FROM '.TABLE_PREFIX."pa_album_comments WHERE album_id=$id";
262                 mysql_query($sql, $db);
263
264                 //delete album
265                 $sql = "DELETE FROM ".TABLE_PREFIX."pa_albums WHERE id=$id";
266                 mysql_query($sql, $db);
267         }
268
269         /** 
270          * Get album photos
271          */
272         function getAlbumPhotos($offset=-1){
273                 global $db;
274                 $id = $this->id;
275                 $offset = intval($offset);
276                 $rows = array();
277
278                 $sql = "SELECT photos.* FROM " .TABLE_PREFIX."pa_photos photos LEFT JOIN ".TABLE_PREFIX."pa_albums albums ON albums.id=photos.album_id WHERE albums.id=$id ORDER BY ordering";
279                 if ($offset >= 0){
280                         $sql .= " LIMIT $offset ,".AT_PA_PHOTOS_PER_PAGE;
281                 }
282
283                 $result = mysql_query($sql, $db);
284                 if ($result){
285                         while ($row = mysql_fetch_assoc($result)){
286                                 $rows[] = $row;
287                         }
288                 }
289                 return $rows;
290         }
291
292         /** 
293          * Get album information
294          * @param       int      album id
295          * @return  the album row, false on error
296          */
297         function getAlbumInfo(){
298                 global $db;
299                 $id = $this->id;
300                 $sql = "SELECT * FROM ".TABLE_PREFIX."pa_albums WHERE id=$id";
301                 $result = mysql_query($sql, $db);
302                 if ($result){
303                         $row = mysql_fetch_assoc($result);
304                         return $row;
305                 }
306                 return false;
307         }
308
309         /** 
310          * Get a list of album by the given type (profile/my albums/class albums)
311          * Default to be all.
312          */
313         function getAlbums($member_id, $type_id=-1, $offset=-1){
314                 global $db;
315                 $type_id = intval($type_id);
316                 $member_id = intval($member_id);
317                 $offset = intval($offset);              
318                 $rows = array();
319                                 
320                 $sql = "SELECT * FROM ".TABLE_PREFIX."pa_albums WHERE member_id=$member_id";
321                 if($type_id==AT_PA_TYPE_COURSE_ALBUM){
322                         //if inside the course scope, get this course's albums only
323                         //if in my_start_page, get all enrolled course
324                         $course_sql = ($_SESSION['course_id']==0)?'':'AND ca.course_id='.$_SESSION['course_id'];
325
326                         $sql = 'SELECT albums.* FROM '.TABLE_PREFIX.'pa_albums albums, 
327                                                 (SELECT ca.* FROM '.TABLE_PREFIX.'course_enrollment enrollments
328                                                         RIGHT JOIN '.TABLE_PREFIX."pa_course_album ca 
329                                                         ON enrollments.course_id=ca.course_id
330                                                         WHERE member_id=$member_id $course_id
331                                                 ) AS allowed_albums
332                                                 WHERE albums.id=allowed_albums.album_id";
333                 }
334                 elseif($type_id > 0){
335                         $sql .= " AND type_id=$type_id";
336                 }
337                 if ($offset > -1){
338                         $sql .= " LIMIT $offset ," . AT_PA_ALBUMS_PER_PAGE;
339                 }
340                 $result = mysql_query($sql, $db);
341                 if($result){
342                         while($row = mysql_fetch_assoc($result)){
343                                 $rows[$row['id']] = $row;
344                         }
345                 }
346                 return $rows;
347         }
348
349         /**
350          * Get all albums, used by Admin only.
351          */
352         function getAllAlbums($offset=-1){
353                 global $db;
354                 $offset = intval($offset);
355
356                 $sql = 'SELECT * FROM '.TABLE_PREFIX.'pa_albums';
357                 
358                 if ($offset > -1){
359                          $sql .= " LIMIT $offset ," . AT_PA_ADMIN_ALBUMS_PER_PAGE;
360                 }
361
362                 $result = mysql_query($sql, $db);
363                 if($result){
364                         while($row = mysql_fetch_assoc($result)){
365                                 $rows[$row['id']] = $row;
366                         }
367                 }
368                 return $rows;
369         }
370
371
372         /**
373          * Get all private/shared albums (ignore album type)
374          * @param       boolean         True to get all shared album; false to get all private album, default: true
375          * @param       int                     Resultset's limit
376          */
377         function getSharedAlbums($isShared=true, $offset=-1){
378                 global $db;
379                 $offset = intval($offset);
380                 $permission = ($isShared)? 1 : 0;
381
382                 $sql = 'SELECT * FROM '.TABLE_PREFIX."pa_albums WHERE permission=$permission";
383                 if ($offset > -1){
384                          $sql .= " LIMIT $offset ," . AT_PA_ALBUMS_PER_PAGE;
385                 }
386                 $result = mysql_query($sql, $db);
387                 if ($result){
388                         while ($row = mysql_fetch_assoc($result)){
389                                 $rows[$row['id']] = $row;
390                         }
391                 }
392                 return $rows;
393         }
394
395         /** 
396          * Get album type names
397          * @param       int             album types, check constants.inc.php
398          * @return      the string representation of this album type
399          */
400         function getAlbumTypeName($type){
401                 switch ($type){
402                         case AT_PA_TYPE_MY_ALBUM:
403                                 return _AT('pa_my_albums');
404                         case AT_PA_TYPE_COURSE_ALBUM:
405                                 return _AT('pa_course_albums');
406                         case AT_PA_TYPE_PERSONAL:
407                                 return _AT('pa_profile_album');
408                         default:
409                                 return false;
410                 }
411         }
412
413         /**
414          * Get the owner of this album
415          * @param       int             album_id
416          * @param       int             member_id
417          * @return      True if the given user has the privilege to delete/edit.
418          */
419         function checkAlbumPriv($member_id){
420                 global $db;
421                 $album_id = $this->id;
422                 $member_id = intval($member_id);
423
424                 //if admin
425                 if (admin_authenticate(AT_ADMIN_PRIV_PHOTO_ALBUM, true)){
426                         return true;
427                 }
428
429                 $sql = "SELECT member_id FROM ".TABLE_PREFIX."pa_albums WHERE id=$album_id";
430                 $result = mysql_query($sql, $db);
431                 if ($result){
432                         $row = mysql_fetch_assoc($result);
433                         return ($row['member_id']==$member_id);
434                 }
435                 return false;
436         }
437
438         /**
439          * Get the owner of this photo
440          * @param       int             photo_id
441          * @param       int             member_id
442          * @return      True if the given user has the privilege to delete/edit.
443          */
444         function checkPhotoPriv($photo_id, $member_id){
445                 global $db;
446                 $photo_id = intval($photo_id);
447                 $member_id = intval($member_id);
448
449                 $sql = "SELECT member_id FROM ".TABLE_PREFIX."pa_photos WHERE id=$photo_id";
450                 $result = mysql_query($sql, $db);
451                 if ($result){
452                         $row = mysql_fetch_assoc($result);
453                         return ($row['member_id']==$member_id);
454                 }
455                 return false;
456         }
457
458
459         /**
460          * Get the owner of the comment
461          */
462         function checkCommentPriv($comment_id, $member_id, $isPhoto){
463                 global $db;
464                 $comment_id = intval($comment_id);
465                 $member_id = intval($member_id);
466
467                 if ($isPhoto){
468                         $sql = "SELECT member_id FROM ".TABLE_PREFIX."pa_photo_comments WHERE id=$comment_id";
469                 } else {
470                         $sql = "SELECT member_id FROM ".TABLE_PREFIX."pa_album_comments WHERE id=$comment_id";
471                 }
472                 $result = mysql_query($sql, $db);
473                 if ($result){
474                         $row = mysql_fetch_assoc($result);
475                         return ($row['member_id']==$member_id);
476                 }
477                 return false;
478         }
479
480         /**
481          * Add comment
482          * @param       int             id (can be photo_id, or album_id)
483          * @param       string  comment 
484          * @param       int             user id
485          * @param       boolean true if it is photo_id, false otherwise
486          */
487         function addComment($id, $comment, $member_id, $isPhoto){
488                 global $addslashes, $db;
489
490                 $id = intval($id);
491                 $member_id = intval($member_id);
492                 $comment = $addslashes($comment);
493
494                 if(!$isPhoto){
495                         $sql =  'INSERT INTO '.TABLE_PREFIX."pa_album_comments (album_id, comment, member_id, created_date) VALUES ($id, '$comment', $member_id, NOW())";
496                 } else {
497                         $sql =  'INSERT INTO '.TABLE_PREFIX."pa_photo_comments (photo_id, comment, member_id, created_date) VALUES ($id, '$comment', $member_id, NOW())";
498                 }
499                 $result = mysql_query($sql, $db);
500                 return $result;
501         }
502
503         /**
504          * Edit comment
505          * @param       int             comment id
506          * @param       string  comment
507          * @param       boolean true if it is photo_id, false otherwise
508          * @precondition        this->member_id has the privilige to edit comment.
509          */
510         function editComment($id, $comment, $isPhoto){
511                 global $addslashes, $db;
512
513                 $id = intval($id);
514                 $comment = $addslashes($comment);
515                 if($id<1 || $comment==''){
516                         return false;
517                 }
518
519                 if (!$isPhoto){
520                         $sql = 'UPDATE '.TABLE_PREFIX."pa_album_comments SET comment='$comment' WHERE id=$id";
521                 } else {
522                         $sql = 'UPDATE '.TABLE_PREFIX."pa_photo_comments SET comment='$comment' WHERE id=$id";
523                 }
524                 $result = mysql_query($sql, $db);
525                 return $result;
526         }
527
528
529         /**
530          * Get comments
531          * @param       int             id (can be photo_id, or album_id)
532          * @param       boolean true of it is photo_id, false otherwise.
533          */
534         function getComments($id, $isPhoto){
535                 global $db;
536                 
537                 $id = intval($id);
538
539                 if ($isPhoto){
540                         $sql = 'SELECT * FROM '.TABLE_PREFIX."pa_photo_comments WHERE photo_id=$id";
541                 } else {
542                         $sql = 'SELECT * FROM '.TABLE_PREFIX."pa_album_comments WHERE album_id=$id";
543                 }
544                 $sql .= ' ORDER BY created_date';
545
546                 $result = mysql_query($sql, $db);
547                 if($result){
548                         while ($row = mysql_fetch_assoc($result)){
549                                 $rows[] = $row;
550                         }
551                 }
552                 return $rows;
553         }
554
555         /**
556          * Delete photo comment 
557          */
558         function deleteComment($id, $isPhoto){
559                 global $db;
560                 $id = intval($id);
561                 
562                 if ($isPhoto){
563                         $sql = "DELETE FROM ".TABLE_PREFIX."pa_photo_comments WHERE id=$id";
564                 } else {
565                         $sql = "DELETE FROM ".TABLE_PREFIX."pa_album_comments WHERE id=$id";
566                 }
567                 mysql_query($sql, $db);
568         }
569
570         /**
571          * Search and return list of albums, and list of photos 
572          * Note: Speed and ranks are of priority here.
573          * @param       Array                   The unescaped array of search phrases.
574          * @return      [Array, Array]  First array is albums, second array are matched photos
575          */
576         function search($words){
577                 global $db, $addslashes;
578                 
579                 //init
580                 $visible_photos = array();
581                 $visible_albums = array();
582
583                 //validate input
584                 if (!is_array($words) || empty($words)){
585                         return null;
586                 }
587                 //filter 
588                 foreach($words as $k=>$v){
589                         $v = $addslashes(trim($v));
590                         $query .= "(description LIKE '%$v%' OR name LIKE '%$v%' OR alt_text LIKE '%$v%') OR ";  //for sql
591                         $pattern .= $v.'|';     //regex for albums
592                 }
593                 $pattern = substr($pattern, 0, -1);
594                 
595                 //TODO: Optimize SQL, UNION is slow, but I think this is the fastest I can get, prove me wrong.
596                 //@harris
597                 /** Get all visible albums */
598                 $sql = 'SELECT albums.* FROM '.TABLE_PREFIX.'pa_albums albums, 
599                                         (SELECT ca.* FROM '.TABLE_PREFIX.'course_enrollment enrollments
600                                                 RIGHT JOIN '.TABLE_PREFIX."pa_course_album ca 
601                                                 ON enrollments.course_id=ca.course_id
602                                                 WHERE member_id=$_SESSION[member_id]
603                                         ) AS allowed_albums
604                                         WHERE albums.id=allowed_albums.album_id
605                                 UNION
606                                 SELECT * FROM AT_pa_albums WHERE member_id=$_SESSION[member_id] OR permission=1";
607                 $result = mysql_query($sql, $db);
608                 if (!$result){
609                         return null;
610                 }
611                 while($row = mysql_fetch_assoc($result)){
612                         $visible_albums[$row['id']] = $row;
613                 }
614                 $visible_albums_ids = implode(', ', array_keys($visible_albums));
615                 
616                 /** Get all photos from these albums */
617                 $sql = 'SELECT * FROM '.TABLE_PREFIX."pa_photos WHERE album_id IN ($visible_albums_ids)";               
618                 $query = ' AND ' . substr($query, 0, -3);
619                 $sql = $sql . $query . ' LIMIT ' . AT_PA_PHOTO_SEARCH_LIMIT; 
620                 $result = mysql_query($sql, $db);
621                 if (!$result){
622                         return null;
623                 }
624                 while($row = mysql_fetch_assoc($result)){
625                         $visible_photos[$row['id']] = $row;
626                 }
627
628                 /** Point system*/
629                 //photos
630                 if (!empty($visible_photos)){
631                         $album_photos = array();        //keep track of the # of photos inside an album, should match a 'count(*) group by'
632                         foreach($visible_photos as $photo_id=>$photo){
633                                 $match_flag = false;
634
635                                 if (preg_match("/$pattern/i", $photo['name'])){
636                                         $visible_photos[$photo_id]['point'] += 1;
637                                         $match_flag = true;
638                                 } 
639                                 if (preg_match("/$pattern/i", $photo['alt_text'])){
640                                         $visible_photos[$photo_id]['point'] += 1;
641                                         $match_flag = true;
642                                 } 
643                                 if (preg_match("/$pattern/i", $photo['description'])){
644                                         $visible_photos[$photo_id]['point'] += 2;
645                                         $match_flag = true;
646                                 }
647                                 //total photo points within an album
648                                 if ($match_flag){
649                                         $album_photos[$photo['album_id']] += 1;
650                                 }
651                         }
652                 }
653
654                 //albums
655                 foreach($visible_albums as $album_id=>$album){
656                         if (preg_match("/$pattern/i", $album['name'])){
657                                 $visible_albums[$album_id]['point'] += 3;
658                         } 
659                         if (preg_match("/$pattern/i", $album['location'])){
660                                 $visible_albums[$album_id]['point'] += 1;
661                         } 
662                         if (preg_match("/$pattern/i", $album['description'])){
663                                 $visible_albums[$album_id]['point'] += 1;
664                         }
665                         //every photo has a certain value to the album, and is calculated as follow 
666                         //[# of matched photo in an album] / [total number of matched photos] *4
667                         //4 is the total matched photo score (ie. all album's photo score should add up to 4)
668                         if (isset($album_photos[$album_id])){
669                                 $visible_albums[$album_id]['point'] += $album_photos[$album_id]/sizeof($visible_photos) * 4;
670                         }
671                         //If no point in the album, most likely it's irrelevant and not of interest, take it out
672                         if (!isset($visible_albums[$album_id]['point'])){
673                                 unset($visible_albums[$album_id]);
674                         }
675                 }
676
677                 /** sort and return */
678                 usort($visible_photos, array('PhotoAlbum', 'search_cmp'));
679                 usort($visible_albums, array('PhotoAlbum', 'search_cmp'));
680 //              debug($visible_photos, 'visible_photos');
681 //              debug($visible_albums, 'visible albums');
682
683                 return array($visible_albums, $visible_photos);
684         }
685         
686         /**
687          * Compare functino for usort, used by search (descending)
688          */
689         function search_cmp($k1, $k2){
690                 if(!isset($k1['point'])){
691                         $k1['point'] = 0;
692                 }
693                 if(!isset($k2['point'])){
694                         $k2['point'] = 0;
695                 }
696
697                 if ($k1['point'] == $k2['point']) return 0;
698                 if ($k1['point'] > $k2['point']) return -1;
699                 else return 1;
700         }
701 }
702 ?>