diff --git a/jorge/COPYING b/jorge/COPYING deleted file mode 100644 index d511905..0000000 --- a/jorge/COPYING +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/jorge/README b/jorge/README deleted file mode 100644 index ef2151a..0000000 --- a/jorge/README +++ /dev/null @@ -1,44 +0,0 @@ -iJorge by Zbyszek Zolkiewski (C) 2009 VERSION 1.5-RC1 - -About. - Jorge is set of php scripts that are front-end for Oleg Palij mod_logdb. - -Licensing. - Jorge is distributed by GPL License provided in COPYING file as well in parts in all source files. -Jorge uses jQuery library and some plugins, please read license info at http://docs.jquery.com/Licensing - -Bug reporting: -If you found any bug or have any improvement idea you can contact me at (email/xmpp): zbyszek@jabster.pl -Patches are most welcome. - -Requirements: -- working ejabberd 2.x (or higher) with mod_logdb (compatibile version is bundled with Jorge) -- mod_xmlrpc - revision 772 -- mysql5 server -- any http server supporting PHP (5.2.x or higher) with gd, mcrypt and xmlrpc support - -Client Requirements: -- Jorge is tested and compatibile with: Firefox 2.x, Firefox 3.x, Opera 9.x, Apple Safri 3.x,4.x and Google Chrome (IE7 and IE8+ may work but it is not recomended due to IE standards violations, IE6 is not supported at all) -- Web-browser _must_ have enabled javascript as Jorge strongly relay on jQuery and other js related scripts -- Cookies must be enabled - -Installing: -- setup XML-RPC facility (mod_xmlrpc, available at http://svn.process-one.net/ejabberd-modules/mod_xmlrpc/trunk/ - Use rev772!) -- copy Jorge files into your http server (sugested vhost over SSL connection). -- set up database for Jorge (install/jorge.sql), see README inside install dir -- copy config.php.inc to config.php and edit file - READ CAREFULLY -- that's it! - -Archive usage: -We can say that 1 milion messeges collected by the server consume approx. 65 Megabytes. Depending on number of users that use your server and -how many will activate logging, you must compute db partitions. - -NO WARRANTY -THE PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -!!!SECURITY NOTICE!!! - -Before use check if you set registered_globals to off. It is *required* for security reasons! -Jorge is compatibile out of the box with: mod_security2 and php-hardened (suhosin) and easy to chroot. -It is strongly recomended to use encrypted sessions. -If you are using Hardened_PHP or Suhosin alter get.max_value_length to some greater value f.e 1024. diff --git a/jorge/calendar_view.php b/jorge/calendar_view.php deleted file mode 100644 index 8c33751..0000000 --- a/jorge/calendar_view.php +++ /dev/null @@ -1,679 +0,0 @@ -set_overview('

'.$cal_head[$lang].'

'.$cal_notice[$lang].'. '.$change_view[$lang].'

'); - -if (isset($_GET['left'])) { - - if ($enc->decrypt_url($_GET['left']) === true) { - - $left = $enc->tslice; - - } - else { - - unset($left); - - } - -} - -if (isset($_GET['right'])) { - - if ($enc->decrypt_url($_GET['right']) === true) { - - $right = $enc->tslice; - - } - else { - - unset($left); - - } - -} - -$e_string = $_GET['a']; -$resource_id = $_GET['b']; -$start = $_GET['start']; -$jump_to = $_POST['jump_box']; - -if ($jump_to!="") { - - $mo=$jump_to; - -} - -if ($mo === "jump") { - - unset($mo); - -} - -if ($enc->decrypt_url($e_string) === true) { - - $tslice = $enc->tslice; - $talker = $enc->peer_name_id; - $server = $enc->peer_server_id; - $action = $enc->action; - $lnk = $enc->lnk; - - // reencode string: - $e_string = $enc->crypt_url("tslice=$tslice&peer_name_id=$talker&peer_server_id=$server"); - -} - -// avoid unnessesary validation, actualy... -if ($tslice) { - - if (validate_date($tslice) === false) { - - debug(DEBUG,"Date validation failed: $tslice"); - unset ($tslice); - unset($e_string); - unset($talker); - unset($left); - unset($right); - unset($mo); - unset($action); - - } - else{ - - debug(DEBUG,"Date set to: $tslice"); - - } - -} - -// some validation things... -if ($start) { - - if ((validate_start($start))!==true) { - - $start="0"; - - } - -} - -// set idx -if ($_GET['idx']) { - - $idx = $_GET['idx']; - - if ($enc->decrypt_url($idx) === true) { - - if($db->set_ext_index($enc->single) !== true) { - - unset($idx); - unset($action); - - } - - $idx = $enc->single; - - } - else{ - - unset($idx); - unset($action); - - } - -} - -// undo delete -if ($action === "undelete") { - - if ($db->move_chat_from_trash($talker,$server,$tslice,$lnk,$idx) === true) { - - $html->status_message($undo_info[$lang],"message"); - - } - else { - - unset($talker); - $html->alert_message($oper_fail[$lang],"message"); - - } - -} - -if ($action === "delete") { - - if ($db->move_chat_to_trash($talker,$server,$tslice,$lnk) === true) { - - $undo = $enc->crypt_url("tslice=$tslice&peer_name_id=$talker&peer_server_id=$server&lnk=$lnk&action=undelete"); - unset($talker); - $idx = $enc->crypt_url("single=".$db->get_last_idx().""); - $html->status_message('
'.$del_moved[$lang] - .' Undo
'); - - } - - else { - - $html->alert_message($oper_fail[$lang],"message"); - unset($talker); - - } - -} - -// check few condition, what we're doing... -if ($tslice!="") { - - list($y,$m,$selected) = split("-", $tslice); - $mo="$y-$m"; - - } - - else { - - if (isset($left)) { - - $mo=$left; - - } - - if (isset($right)) { - - $mo=$right; - - } - -} - -if (!isset($mo)) { - - $mo = date("Y-n"); - -} - -// validate mo if fail, silently fallback to current date -if (validate_date($mo."-1") === false) { - - unset ($tslice); - unset ($e_string); - unset ($talker); - $mo = date("Y-m"); - -} - -// master div -$html->set_body('
'); - -// calendar div -if ($talker) { - - $float="left;"; - - } - else { - - $float="none;"; - -} - -// select list -$db->get_user_stats_drop_down(); -$ch_mo = $db->result; - -// check if user have some chats -if (count($ch_mo)!=0) { - - $html->set_body('
-
-
'); - - // now generate calendar - $db->get_user_stats_calendar($mo); - $result_for_days = $db->result; - - $i=0; - // days - foreach($result_for_days as $result) { - - $i++; - $days[$i] = str_replace("-","",$result[days]); - - } - - list($y,$m) = split("-", $mo); - $html->set_body(calendar($db,$user_id,$xmpp_host,$y,$m,$days,TOKEN,$url_key,$left,$right,$selected,$lang,$view_type,1,$null_a=0,$null_b=0,$cal_days,$enc,$months_names,$weekdays)); - unset($days); - - } - else { - - $html->status_message($no_archives[$lang]); - -} - -// if we got day, lets display chats from that day but only if there are some -if ($tslice) { - - $db->get_user_chats($tslice); - $result = $db->result; - if (count($result)>0) { - - $display_conversations = true; - - } - else{ - - $display_conversations = false; - - } - -} - -if ($display_conversations === true) { - - // we need to sort list by nickname so we need to combine 2 results: roster and mod_logdb chatlist: - foreach($result as $sort_me) { - - $roster_name = query_nick_name($ejabberd_roster,$sort_me[username],$sort_me[server_name]); - $arr_key++; - - if (!$roster_name) { - - // split contact into 2 arrays: one with full jids, second without names - transports, agents.. - $sorted_spec[$arr_key] = array( - "roster_name"=>$roster_name, - "username"=>$sort_me[username], - "server_name"=>$sort_me[server_name], - "todaytalk"=>$sort_me[todaytalk], - "server"=>$sort_me[server], - "lcount"=>$sort_me[lcount] - ); - } - else { - - $sorted_list[$arr_key] = array( - "roster_name"=>$roster_name, - "username"=>$sort_me[username], - "server_name"=>$sort_me[server_name], - "todaytalk"=>$sort_me[todaytalk], - "server"=>$sort_me[server], - "lcount"=>$sort_me[lcount] - ); - } - - } - // sort and split two lists: normal contacts and special contacts. - asort($sorted_list); - - if (!$show_spec) { - - $show_spec="1"; - - } - - if ($sorted_spec AND $show_spec === "1") { - - if ($sorted_list) { - - $sorted_list = array_merge($sorted_list,$sorted_spec); - - } - else{ - - $sorted_list = $sorted_spec; - - } - - } - - $html->set_body(' - - - - - - - - - - - - - - - - -
- - - - - - - -
'.$chat_list_l[$lang].'
- '); - - // select chatters - foreach ($sorted_list as $entry) { - - $user_name = $entry[username]; - $server_name = $entry[server_name]; - if ($talker==$entry["todaytalk"] AND $server==$entry[server]) { - - $bold_b=""; - $bold_e=""; - $mrk=1; - - } - else { - - $bold_b=""; - $bold_e=""; - $mrk=0; - - } - - $nickname = $entry[roster_name]; - if (!$nickname) { - - $calday_class="caldays4"; - $nickname = $not_in_r[$lang]; - $spec_con = '
('.htmlspecialchars($server_name).')'; - unset($malpa); - - } - else { - - $calday_class="caldays3"; - unset($spec_con); - $malpa = "@"; - - } - - if ($mrk==1) { - - $db->get_next_prev_day($entry[todaytalk],$entry[server],$tslice,"p"); - $previous_t = $db->result->at; - $to_base_prev = $enc->crypt_url("tslice=$previous_t&peer_name_id=$entry[todaytalk]&peer_server_id=$entry[server]"); - - $db->get_next_prev_day($entry[todaytalk],$entry[server],$tslice,"n"); - $next_t = $db->result->at; - $to_base_next = $enc->crypt_url("tslice=$next_t&peer_name_id=$entry[todaytalk]&peer_server_id=$entry[server]"); - - } - - $to_base2 = $enc->crypt_url("tslice=$tslice&peer_name_id=$entry[todaytalk]&peer_server_id=$entry[server]"); - if ($mrk==1 AND $previous_t != NULL) { - - $html->set_body('<<< '); - - } - - $html->set_body(''.$bold_b.cut_nick($nickname).$bold_e.''); - - if ($mrk==1 AND $next_t != NULL) { - - $html->set_body(' >>>'); - } - - if ($spec_con) { - - $html->set_body($bold_b.$spec_con.$bold_e); - - } - - $html->set_body('
'); - - } - - $html->set_body(' -
-
- '); -} - -$html->set_body('
'); - -// Chat thread: -if ($talker) { - - $html->set_body(''); - if (!$start) { - - $start="0"; - - } - $db->get_num_lines($tslice,$talker,$server); - $nume = $db->result->cnt; - if ($start>$nume) { - - $start=$nume-$num_lines_bro; - - } - - $db->get_user_name($talker); - $talker_name = $db->result->username; - $db->get_server_name($server); - $server_name = $db->result->server_name; - $nickname = query_nick_name($ejabberd_roster,$talker_name,$server_name); - if ($nickname === "") { - - $nickname=$not_in_r[$lang]; - $spec_mark = true; - - } - else { - - $spec_mark = false; - - } - - $predefined = $enc->crypt_url("jid=$talker_name@$server_name"); - - $html->set_body('
- - '); - - if ($_GET['loc']) { - - $loc_id=$_GET['loc']; - if ($loc_id=="2") { - - $back_link_message=$chat_map_back[$lang]; - $back_link="chat_map.php?chat_map=$predefined"; - - } - elseif($loc_id=="3") { - - $back_link_message=$fav_back[$lang]; - $back_link="favorites.php"; - - } - elseif($loc_id=="4") { - - $back_link_message=$myl_back[$lang]; - $back_link="my_links.php"; - - } - $html->set_body(''); - - } - if ($resource_id) { - - $db->get_resource_name($resource_id); - $res_display = $db->result->resource_name; - $html->set_body(''); - - } - - $action_link = $enc->crypt_url("tslice=$tslice&peer_name_id=$talker&peer_server_id=$server&lnk=$e_string&action=delete"); - $sess->set('export_nickname',$nickname); // pass to export - $html->set_body(' - - - - - - '); - - if($db->get_user_chat($tslice,$talker,$server,$resource_id,$start,$num_lines_bro) === false) { - - $html->alert_message($oper_fail[$lang]); - - } - // processing messages. this should be handled as separate message_processor, so that tree view and calendar view can share the same code withoud redundancy. To be done in 2.0 - $result = $db->result; - - // some strings to pass to message_processor - $lang_pack = array( - $cont_chat_p[$lang], - $message_type_message[$lang], - $message_type_error[$lang], - $message_type_headline[$lang], - $resource_only[$lang], - $muc_message[$lang], - $my_links_save[$lang], - $verb_h[$lang], - $in_min[$lang], - $cont_chat[$lang] - ); - - // Sent all data to parsing function (message processor) - if (message_processor($tslice,$server_name,$start,$nickname,$result,$db,$html,$enc,TOKEN,$split_line,$lang_pack,$lang,$spec_mark,$e_string,$to_base_prev,$to_base_next) !== true) { - - $html->alert_message($oper_fail[$lang]); - $html->destroy_content(); - - } - - // limiting code - $html->set_body(''); - // limiting code - end - - if (($nume-$start)>40) { - - $html->set_body(''); - - } - - $html->set_body('
-
'.$back_link_message.'
'.$resource_warn[$lang].cut_nick(htmlspecialchars($res_display)).'. ' - .$resource_discard[$lang].''.$resource_discard2[$lang].'
'.$time_t[$lang].' '.$user_t[$lang].' '.$thread[$lang].' - '); - - // check favorite - $db->check_favorite($talker,$server,$tslice); - if ($db->result->cnt < 1) { - - $html->set_body(' -
- - - -
- '); - } - else { - - $html->set_body(' -
- - - '.$fav_favorited[$lang].' -
- '); - - - } - - $html->set_body(''.$export_link[$lang].'  |  '.$all_for_u[$lang].' - '.$all_for_u_m2[$lang].' -  |  - '.$all_for_u_m[$lang].' -   |   - '.$del_t[$lang].' -
'); - - for($i=0;$i < $nume;$i=$i+$num_lines_bro){ - - if ($i!=$start) { - - if ($resource_id) { - - $add_res="&b=$resource_id"; - } - else { - - $add_res=""; - } - - $html->set_body(' ['.$i.'] '); - } - - else { - - $html->set_body('-'.$i.'- '); - - } - - } - - $html->set_body('
'.$back_t[$lang].'
'); -} - -$html->set_body('
'); - -require_once("footer.php"); -?> diff --git a/jorge/chat_map.php b/jorge/chat_map.php deleted file mode 100644 index cc64e3a..0000000 --- a/jorge/chat_map.php +++ /dev/null @@ -1,152 +0,0 @@ -set_overview('

'.$chat_map[$lang].'

'.''.$chat_select[$lang].''); - -if ($_POST['chat_map']) { - - $con_map = $enc->decrypt_url($_POST['chat_map']); - - } - elseif ($_GET['chat_map']) { - - $con_map = $enc->decrypt_url($_GET['chat_map']); - - } - -if($con_map === true) { - - $con_map = $enc->jid; - } - else{ - - unset($con_map); -} - -// prepare roster object -$ejabberd_roster->sort_by_nick("az"); -$roster_chat = $ejabberd_roster->get_roster(); - -$html->set_body('


-
-

'.$filter_tip[$lang].'

- '.$chat_m_select[$lang].' -
'); - -if ($con_map AND $_POST['chat_map'] != "null") { - - // split username and server name - list($name_peer,$server_peer) = split("@",$con_map); - - // get the id's of user and server - $db->get_user_id($name_peer); - $peer_name_id = $db->result->user_id; - $db->get_server_id($server_peer); - $peer_server_id = $db->result->server_id; - - if ($peer_name_id !== null AND $peer_server_id !== null) { - - //first get the months - $db->get_chat_map($peer_name_id,$peer_server_id); - $result1 = $db->result; - $cc_cmp = count($result1); - foreach ($result1 as $row_m) { - - // hack for proper date parsing - list($y,$m) = split("-",$row_m[at]); - $mo="$y-$m"; - - // now get the days in with user was talking - $db->get_chat_map_specyfic($peer_name_id,$peer_server_id,$mo); - $result2 = $db->result; - - foreach($result2 as $row_day) { - - // now scan day for chats, yep thats weak, but as long as we dont have right stats table this will work... - $i++; - list($y,$m,$d) = split("-",$row_day[at]); - $days[$i] = $d; - } - - if (count($days)>=1) { - - $html->set_body('
'); - $html->set_body(calendar($db,$user_id,$xmpp_host,$y,$m,$days,TOKEN,$url_key,$left,$right,$selected,$lang,$view_type,2,$peer_name_id,$peer_server_id,$cal_days,$enc,$months_names,$weekdays)); - $html->set_body('
'); - unset($days); - - } - else { - - $score++; - - } - $i=0; - - } - - } - - else { - - $cc_cmp = $score; - } - - - if ($score==$cc_cmp) { - - $html->set_body('

'.$chat_no_chats[$lang].'

'); - - } - -} - -$html->set_body('
*-'.$ff_notice[$lang].''); -require_once("footer.php"); -?> diff --git a/jorge/class.db.php b/jorge/class.db.php deleted file mode 100644 index 2ee23c4..0000000 --- a/jorge/class.db.php +++ /dev/null @@ -1,3096 +0,0 @@ -setData($db_host,$db_name,$db_user,$db_password,$db_driver,$xmpp_host); - - } - - - private function setData($db_host,$db_name,$db_user,$db_password,$db_driver,$xmpp_host) { - - $this->db_host = $db_host; - $this->db_name = $db_name; - $this->db_user = $db_user; - $this->db_password = $db_password; - $this->db_driver = $db_driver; - $this->xmpp_host = $this->sql_validate($xmpp_host,"string"); - $this->vhost = str_replace("_",".", $this->sql_validate($xmpp_host,"string")); - - try { - - $this->db_connect(); - - } - catch(Exception $e) { - - echo "
Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); - - } - - if ($this->vhost) { - - $this->set_ignore_id(); - - } - - } - - private function db_mysql() { - - $conn = mysql_connect("$this->db_host", "$this->db_user", "$this->db_password"); - if (!$conn) { - - return false; - - } - if (mysql_select_db($this->db_name)) { - - return true; - - } - - else { - - return false; - - } - - } - - private function do_query($query) { - - $this->show_debug_info($query, $time = false); - if ($this->is_error === false) { - - $this->time_start(); - $result = mysql_query($query); - $this->time_end(); - $this->show_debug_info($query = null, $time = true); - - } - elseif($this->is_error === true) { - - if ($this->is_debug === true) { - if ($this->is_debug === true) { - - throw new Exception("Error before queryID:".$this->id_query,3); - } - } - return false; - } - - if ($result === false ) { - - $this->is_error = true; - if ($this->is_debug === true) { - - throw new Exception("Query error in QueryID:".$this->id_query,2); - } - return false; - - } - else { - - if ($this->query_type === "select" OR $this->query_type="create_table") { - - return $result; - } - elseif($this->query_type === "update" OR $this->query_type === "insert" OR $this->query_type === "replace") { - - return mysql_affected_rows(); - } - elseif($this->query_type === "delete") { - - return $result; - - } - elseif($this->query_type === "transaction") { - - return $result; - - } - } - - return false; - - } - - private function db_query($query) { - - try { - - $result = $this->do_query($query); - - } - catch (Exception $e) { - - echo "
Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); - return false; - } - - return $result; - } - - private function db_connect() { - - if ($this->db_driver === "mysql") { - - if ($this->db_mysql() === true) { - - return true; - } - else { - $this->is_error = true; - if ($this->is_debug === true) { - - throw new Exception("
DB Connection failed!",1); - } - } - } - - return false; - - } - - private function select($query,$return_type = null) { - - $this->query_type="select"; - if (strpos(strtolower($query),"select") === 0) { - - try{ - $this->result = $this->db_query($query); - } - catch(Exception $e) { - echo "
Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); - } - - if($this->is_error===false) { - - if($return_type === null) { - - $this->result = mysql_fetch_object($this->result); - - } - elseif($return_type === "raw") { - - return true; - - } - - return true; - - } - - else{ - - return false; - - } - - } - - else { - - return false; - - } - } - - private function update($query) { - - $this->query_type = "update"; - if (strpos(strtolower($query),"update") === 0) { - - try{ - $this->result = $this->db_query($query); - } - catch(Exception $e) { - echo "
Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); - } - - if($this->is_error===false) { - - return true; - - } - - else{ - - return false; - - } - - } - - else { - - return false; - - } - } - - private function insert($query) { - - $this->query_type = "insert"; - if (strpos(strtolower($query),"insert") === 0) { - - try{ - $this->result = $this->db_query($query); - } - catch(Exception $e) { - echo "
Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); - } - - if($this->is_error===false) { - - return true; - - } - - else{ - - return false; - - } - - } - - else { - - return false; - - } - } - - private function delete($query) { - - $this->query_type = "delete"; - if (strpos(strtolower($query),"delete") === 0) { - - try{ - $this->result = $this->db_query($query); - } - catch(Exception $e) { - echo "
Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); - } - - if ($this->is_error===false) { - - return true; - - } - else { - - return false; - - } - - } - else { - - return false; - - } - } - - private function replace_q($query) { - - $this->query_type = "replace"; - if (strpos(strtolower($query),"replace") === 0) { - - try{ - $this->result = $this->db_query($query); - } - catch(Exception $e) { - echo "
Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); - } - - if ($this->is_error === false) { - - return true; - - } - else { - - return false; - - } - - } - else { - - return false; - - } - } - - public function begin() { - - $this->id_query = "Q001"; - $this->query_type = "transaction"; - return $this->db_query("begin"); - - } - - public function commit() { - - $this->id_query = "Q002"; - $this->query_type = "transaction"; - return $this->db_query("commit"); - - } - - public function rollback() { - - $this->id_query = "Q003"; - $this->query_type = "transaction"; - $this->is_error = false; - return $this->db_query("rollback"); - - } - - public function get_mylinks_count() { - - $this->id_query = "Q004"; - $this->vital_check(); - $query="SELECT - count(id_link) as cnt - FROM - jorge_mylinks - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - ext is NULL - - "; - - return $this->select($query); - } - - public function get_trash_count() { - - $this->id_query = "Q005"; - $this->vital_check(); - $query="SELECT - count(*) as cnt - FROM - pending_del - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - "; - - return $this->select($query); - - } - - private function row_count($query) { - - $this->id_query = "Q006"; - $result = mysql_num_rows($this->db_query($query)); - if ($result === false) { - - return false; - - } - else{ - - $this->result = $result; - return true; - - } - - } - - public function get_user_id($user) { - - $this->id_query = "Q007"; - $user = $this->sql_validate($user,"string"); - $query="SELECT - user_id - FROM - `logdb_users_".$this->xmpp_host."` - WHERE - username = '$user' - - "; - - return $this->select($query); - - } - - public function get_user_name($user_id,$vhost = null) { - - $this->id_query = "Q008"; - $user_id = $this->sql_validate($user_id,"integer"); - if ($vhost !== null) { - - $vh = $this->vh($vhost,true); - - } - else{ - - $vh = $this->xmpp_host; - - - } - $query="SELECT - username - FROM - `logdb_users_".$vh."` - WHERE - user_id = '$user_id' - - "; - - return $this->select($query); - - } - - public function get_server_id($server) { - - $this->id_query = "Q009"; - $server = $this->sql_validate($server,"string"); - $query="SELECT - server_id - FROM - `logdb_servers_".$this->xmpp_host."` - WHERE - server = '$server' - - "; - - return $this->select($query); - - } - - public function get_server_name($server_id,$vhost = null){ - - $this->id_query = "Q010"; - $server_id = $this->sql_validate($server_id,"integer"); - if ($vhost !== null) { - - $vh = $this->vh($vhost,true); - - } - else{ - - $vh = $this->xmpp_host; - - - } - $query="SELECT - server as server_name - FROM - `logdb_servers_".$vh."` - WHERE - server_id = '$server_id' - - "; - - return $this->select($query); - - } - - public function get_resource_name($resource_id) { - - $this->id_query = "Q012"; - $resource_id = $this->sql_validate($resource_id,"integer"); - $query="SELECT - resource as resource_name - FROM - `logdb_resources_".$this->xmpp_host."` - WHERE - resource_id = '$resource_id' - - "; - - return $this->select($query); - } - - public function get_resource_id($resource) { - - $this->id_query = "Q013"; - $resource = $this->sql_validate($resource,"string"); - $query="SELECT - resource_id - FROM - `logdb_resources_".$this->xmpp_host."` - WHERE - resource = '$resource' - - "; - - return $this->select($query); - - } - - public function get_user_talker_stats($peer_name_id,$peer_server_id){ - - $this->id_query = "Q014"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $query="SELECT - at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - ORDER BY - str_to_date(at,'%Y-%m-%d') - ASC - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("at")); - } - - public function get_num_lines($tslice,$peer_name_id,$peer_server_id) { - - $this->id_query = "Q015"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $table = $this->construct_table($this->tslice); - $query="SELECT - count(timestamp) as cnt - FROM - `$table` - WHERE - owner_id = '".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - - "; - - return $this->select($query); - - } - - public function is_log_enabled() { - - $this->id_query = "Q016"; - - // Return false on non-digit characters, workaround for user not being in sql dictionary. - if (!ctype_digit($this->user_id)) { - - return false; - - } - - $query="SELECT - dolog_default as is_enabled - FROM - `logdb_settings_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - "; - - if ($this->select($query) === true) { - - if ($this->result->is_enabled === "0") { - - $this->result->is_enabled = false; - return true; - - } - elseif($this->result->is_enabled === "1") { - - $this->result->is_enabled = true; - return true; - - } - else{ - - $this->result->is_enabled = null; - return true; - - } - - - - } - - return false; - - } - - public function total_messages($vhost = null) { - - $this->id_query = "Q017"; - if ($vhost === null) { - - $vh = $this->xmpp_host; - - } - else{ - - $vh = $this->vh($vhost,true); - - } - $query="SELECT - sum(count) as total_messages, - count(owner_id) as total_chats - FROM - `logdb_stats_".$vh."` - "; - - $this->select($query,"raw"); - return $this->commit_select(array("total_messages","total_chats")); - - } - - public function total_chats() { - - $this->id_query = "Q018"; - $query="SELECT - count(owner_id) as total_chats - FROM - `logdb_stats_".$this->xmpp_host."` - "; - return $this->select($query); - - } - - public function get_log_list() { - - $this->id_query = "Q019"; - $this->vital_check(); - $query="SELECT - donotlog_list as donotlog - FROM - `logdb_settings_".$this->xmpp_host."` - WHERE - owner_id = '".$this->user_id."' - "; - - $this->select($query); - $split = explode("\n",$this->result->donotlog); - $this->result = $split; - return true; - - } - - public function set_log($bool) { - - $this->id_query = "Q020"; - $this->vital_check(); - if ($bool === true) { - - $val = 1; - - } - elseif($bool === false) { - - $val = 0; - - } - else{ - - return false; - } - - $query="UPDATE - `logdb_settings_".$this->xmpp_host."` - SET - dolog_default = '$val' - WHERE - owner_id = '".$this->user_id."' - "; - - return $this->update($query); - - } - - public function set_logger($event_id,$event_level,$extra = null) { - - $this->id_query = "Q021"; - $this->vital_check(); - $id_log_detail = $this->sql_validate($event_id,"integer"); - $id_log_level = $this->sql_validate($event_level,"integer"); - $extra = $this->sql_validate($extra,"string"); - $query="INSERT INTO - jorge_logger (id_user,id_log_detail,id_log_level,log_time,extra,vhost) - VALUES - ('".$this->user_id."','$id_log_detail','$id_log_level',NOW(),'$extra','".$this->vhost."') - - "; - - return $this->insert($query); - } - - public function get_user_stats_drop_down() { - - $this->id_query = "Q022"; - $this->vital_check(); - if ($this->spec_ignore === true) { - - $sql = "AND peer_name_id != '".$this->ignore_id."'"; - - } - $query="SELECT - substring(at,1,7) as at_send, - at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id = '".$this->user_id."' - $sql - GROUP BY - substring(at,1,7) - ORDER BY - str_to_date(at,'%Y-%m-%d') - DESC - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("at_send","at")); - } - - public function get_user_stats_calendar($mo) { - - $this->id_query = "Q023"; - $this->vital_check(); - $mo = $this->sql_validate($mo,"string"); - if ($this->spec_ignore === true) { - - $sql = "AND peer_name_id != '".$this->ignore_id."'"; - - } - $query="SELECT - distinct(substring(at,8,9)) as days - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id = '".$this->user_id."' - AND - at like '$mo-%' - $sql - ORDER BY - str_to_date(at,'%Y-%m-%d') - DESC - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("days")); - } - - public function get_user_chats($tslice) { - - $this->id_query = "Q024"; - $this->vital_check(); - $xmpp_host = $this->xmpp_host; - $tslice_table = $this->sql_validate($tslice,"string"); - $query="SELECT - a.username, - b.server as server_name, - c.peer_name_id as todaytalk, - c.peer_server_id as server, - c.count as lcount - FROM - `logdb_users_$xmpp_host` a, - `logdb_servers_$xmpp_host` b, - `logdb_stats_$xmpp_host` c - WHERE - c.owner_id = '".$this->user_id."' - AND - a.user_id=c.peer_name_id - AND - b.server_id=c.peer_server_id - AND - c.at = '$tslice' - ORDER BY - lower(username) - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("username","server_name","todaytalk","server","lcount")); - - } - - public function get_user_chat($tslice,$peer_name_id,$peer_server_id,$resource_id = null,$start = null,$num_lines = null) { - - $this->id_query = "Q025"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - if ($resource_id !== null) { - - $resource_id = $this->sql_validate($resource_id,"integer"); - $sql = "AND (peer_resource_id='$resource_id' OR peer_resource_id='1')"; - - } - else{ - - settype($sql,"null"); - } - - $offset_start = $start; - if ($offset_start === null) { - - $offset_start = "0"; - - } - - $offset_end = $start + $num_lines; - $offset_start = $this->sql_validate($offset_start,"integer"); - $offset_end = $this->sql_validate($offset_end,"integer"); - $tslice_table = $this->construct_table($this->tslice); - $query="SELECT - from_unixtime(timestamp+0) as ts, - direction, - type, - subject, - peer_name_id, - peer_server_id, - peer_resource_id, - body - FROM - `$tslice_table` - FORCE INDEX - (search_i) - WHERE - owner_id = '".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - $sql - AND - ext is NULL - ORDER BY - ts - LIMIT - $offset_start,$offset_end - "; - - $this->select($query,"raw"); - return $this->commit_select(array("ts","direction","type","subject","peer_name_id","peer_server_id","peer_resource_id","body")); - - } - - public function get_uniq_chat_dates($limit_start = null, $limit_end = null, $limited = false, $start = null, $peer_name_id = null, $peer_server_id = null) { - - $this->id_query = "Q026"; - $this->vital_check(); - $user_id = $this->user_id; - $xmpp_host = $this->xmpp_host; - if ($limit_start !== null AND $limit_end !== null) { - - $limit_start = $this->sql_validate($limit_start,"date"); - $limit_end = $this->sql_validate($limit_end,"date"); - $sql=" AND str_to_date(at,'%Y-%m-%d') >= str_to_date('$limit_start','%Y-%m-%d') AND str_to_date(at,'%Y-%m-%d') <= str_to_date('$limit_end','%Y-%m-%d')"; - - } - else{ - - settype($sql,"null"); - - } - - if ($limited === true) { - - if ($start == "" OR $start === null) { - - $start = "0"; - - } - - $start = $this->sql_validate($start,"integer"); - $sql2=" limit $start,10000"; - - } - else{ - - settype($sql2,"null"); - - } - - if ($peer_name_id !== null AND $peer_server_id !== null) { - - $peer_name_id = $this->sql_validate($peer_name_id,"integer"); - $peer_server_id = $this->sql_validate($peer_server_id,"integer"); - $sql3 = "AND peer_name_id = '$peer_name_id' AND peer_server_id = '$peer_server_id'"; - - } - else{ - - settype($sql3,"null"); - - } - - $query="SELECT - distinct(at) - FROM - `logdb_stats_$xmpp_host` - WHERE - owner_id='$user_id' $sql3 $sql - ORDER BY - str_to_date(at,'%Y-%m-%d') - ASC - $sql2 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("at")); - - } - - public function check_thread($tslice,$peer_name_id,$peer_server_id,$begin_hour,$end_hour) { - - $this->id_query = "Q027"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $xmpp_host = $this->xmpp_host; - $tslice_table = $this->construct_table($this->tslice); - $query="SELECT - 1 - FROM - `$tslice_table` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - from_unixtime(timestamp) >= str_to_date('".$this->tslice." $begin_hour','%Y-%m-%d %H:%i:%s') - AND - from_unixtime(timestamp) <= str_to_date('".$this->tslice." $end_hour','%Y-%m-%d %H:%i:%s') - ORDER BY - from_unixtime(timestamp) - - "; - - return $this->row_count($query); - - } - - public function get_chat_map($peer_name_id,$peer_server_id) { - - $this->id_query = "Q028"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $query="SELECT - substring(at,1,7) as at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - GROUP BY - substring(at,1,7) - ORDER BY - str_to_date(at,'%Y-%m-%d') - ASC - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("at")); - - } - - public function get_chat_map_specyfic($peer_name_id,$peer_server_id,$month) { - - $this->id_query = "Q029"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $mo = $this->sql_validate($month,"string"); - $query="SELECT - at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - at like '$mo-%' - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("at")); - - } - - public function add_mylink($peer_name_id,$peer_server_id,$link_date,$link,$desc) { - - $this->id_query = "Q030"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $datat = $this->sql_validate($link_date,"string"); - $lnk = $this->sql_validate($link,"string"); - $desc = $this->sql_validate($desc,"string"); - $query="INSERT INTO - jorge_mylinks (owner_id,peer_name_id,peer_server_id,datat,link,description,vhost) - VALUES ( - '".$this->user_id."', - '".$this->peer_name_id."', - '".$this->peer_server_id."', - '$datat', - '$lnk', - '$desc', - '".$this->vhost."' - ) - - "; - - return $this->insert($query); - - } - - public function del_mylink($link_id) { - - $this->id_query = "Q031"; - $this->vital_check(); - $link_id = $this->sql_validate($link_id,"integer"); - $query="DELETE FROM - jorge_mylinks - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - id_link='$link_id' - - "; - - return $this->delete($query); - - } - - public function get_mylink() { - - $this->id_query = "Q032"; - $this->vital_check(); - $query="SELECT - id_link, - peer_name_id, - peer_server_id, - datat, - link, - description, - ext - FROM - jorge_mylinks - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - ext is NULL - ORDER BY - str_to_date(datat,'%Y-%m-%d') - DESC - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("id_link","peer_name_id","peer_server_id","datat","link","description","ext")); - - - } - - public function update_log_list($log_list) { - - $this->id_query = "Q033"; - $this->vital_check(); - $log_list = $this->sql_validate($log_list,"string"); - $query="UPDATE - `logdb_settings_".$this->xmpp_host."` - SET - donotlog_list='$log_list' - WHERE - owner_id='".$this->user_id."' - "; - return $this->update($query); - - } - - public function logger_get_events($event_id = null,$level_id = null, $offset = null,$lang = null) { - - $this->id_query = "Q034"; - $this->vital_check(); - $offset = $this->sql_validate($offset,"integer"); - if ($event_id !== null) { - - $event_id = $this->sql_validate($event_id,"integer"); - $sql_1 = "and id_log_detail='$event_id'"; - - } - if ($level_id !== null) { - - $level_id = $this->sql_validate($level_id,"integer"); - $sql_2 = "and id_log_level='$level_id'"; - - } - $query="SELECT - b.id_event, - b.event AS event, - c.level AS level, - c.id_level, - a.log_time, - a.extra - FROM - jorge_logger a, - jorge_logger_dict b, - jorge_logger_level_dict c - WHERE - a.id_log_detail=b.id_event - AND - c.id_level=a.id_log_level - AND - id_user='".$this->user_id."' - AND - a.vhost='".$this->vhost."' - AND - b.lang = '$lang' - AND - c.lang = '$lang' - - $sql_1 - $sql_2 - - ORDER BY - log_time - DESC LIMIT - $offset,300 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("id_event","event","level","id_level","log_time","extra")); - - } - - public function get_num_events($event_id = null,$level_id = null) { - - $this->id_query = "Q035"; - $this->vital_check(); - if ($event_id !== null) { - - $event_id = $this->sql_validate($event_id,"integer"); - $sql_1 = "AND id_log_detail='$event_id'"; - } - if ($level_id !== null) { - - $level_id = $this->sql_validate($level_id,"integer"); - $sql_2 = "AND id_log_level='$level_id'"; - } - $query="SELECT - count(id_user) AS cnt - FROM - jorge_logger - WHERE - id_user='".$this->user_id."' - AND - vhost='".$this->vhost."' - - $sql_1 - $sql_2 - "; - - return $this->select($query); - - } - - public function get_trashed_items() { - - $this->id_query = "Q036"; - $this->vital_check(); - $query="SELECT - peer_name_id, - peer_server_id, - date, - timeframe, - type, - idx - FROM - pending_del - WHERE - owner_id = '".$this->user_id."' - AND - vhost='".$this->vhost."' - ORDER BY - str_to_date(date,'%Y-%m-%d') - DESC - "; - - $this->select($query,"raw"); - return $this->commit_select(array("peer_name_id","peer_server_id","date","timeframe","type","idx")); - - } - - public function move_chat_to_trash($peer_name_id,$peer_server_id,$tslice,$link) { - - $this->id_query = "Q037"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $xmpp_host = $this->xmpp_host; - $table = $this->construct_table($this->tslice); - - if ($this->get_ext_index($table) !== true) { - - return false; - - } - else{ - - if (!$this->result->idx) { - - $this->ext_idx = "1"; - - } - else{ - - $this->ext_idx = $this->result->idx; - - } - - } - - $this->begin(); - if ($this->set_undo_table($this->peer_name_id,$this->peer_server_id,$this->tslice,"chat") === false) { - - $this->rollback(); - return false; - - } - - if ($this->remove_user_stats($this->peer_name_id,$this->peer_server_id,$this->tslice) === false) { - - $this->rollback(); - return false; - - } - - if ($this->move_mylink_to_trash($peer_name_id,$link) === false) { - - $this->rollback(); - return false; - - } - - if ($this->move_fav_to_trash($peer_name_id,$peer_server_id,$tslice) === false) { - - $this->rollback(); - return false; - - } - - $this->id_query = "Q037a"; - $query="UPDATE - `$table` - SET - ext = '".$this->ext_idx."' - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - ext is NULL - - "; - - if ($this->update($query) === false) { - - $this->rollback(); - return false; - - } - else{ - - $this->commit(); - $this->set_logger("4","1"); - return true; - } - } - - private function remove_user_stats($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q038"; - $query="DELETE FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='$peer_name_id' - AND - peer_server_id='$peer_server_id' - AND - at='$tslice' - "; - - return $this->delete($query); - - } - - public function move_mylink_to_trash($peer_name_id,$link) { - - $this->id_query = "Q039"; - $this->vital_check(); - $peer_name_id = $this->sql_validate($peer_name_id,"integer"); - $lnk = $this->sql_validate($link,"string"); - $query="UPDATE - jorge_mylinks - SET - ext='".$this->ext_idx."' - WHERE - owner_id ='".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - peer_name_id='$peer_name_id' - AND - link like '$lnk%' - AND - ext is NULL - "; - - return $this->update($query); - - } - - public function move_fav_to_trash($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q040"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $query="UPDATE - jorge_favorites - SET - ext='".$this->ext_idx."' - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - tslice='".$this->tslice."' - AND - vhost='".$this->vhost."' - AND - ext is NULL - "; - - return $this->update($query); - - } - - private function set_undo_table($peer_name_id,$peer_server_id,$tslice,$type = null) { - - $this->id_query = "Q041"; - $query="INSERT INTO - pending_del(owner_id,peer_name_id,date,peer_server_id,type,idx,vhost) - VALUES ( - '".$this->user_id."', - '$peer_name_id', - '$tslice', - '$peer_server_id', - '$type', - '".$this->ext_idx."', - '".$this->vhost."' - ) - - "; - - return $this->insert($query); - - } - - private function unset_undo_table($peer_name_id,$peer_server_id,$tslice,$type = null) { - - $this->id_query = "Q042"; - $query="DELETE FROM - pending_del - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='$peer_name_id' - AND - date='$tslice' - AND - peer_server_id='$peer_server_id' - AND - idx = '".$this->ext_idx."' - AND - vhost='".$this->vhost."' - "; - - return $this->delete($query); - } - - public function move_chat_from_trash($peer_name_id,$peer_server_id,$tslice,$link,$idx = null) { - - $this->id_query = "Q043"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $xmpp_host = $this->xmpp_host; - $table = $this->construct_table($this->tslice); - if (!$idx) { - - $this->ext_idx = "1"; - } - else{ - - if (ctype_digit($idx)) { - - $this->ext_idx = $idx; - - } - else{ - - return false; - - } - - } - - // Message tables are not transactional, so this make some trouble for us to control all error conditions :/ - $query="UPDATE - `$table` - SET - ext = NULL - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - ext = '".$this->ext_idx."' - "; - - if ($this->update($query) === false) { - - return false; - - } - - $this->begin(); - if ($this->unset_undo_table($this->peer_name_id,$this->peer_server_id,$this->tslice) === false) { - - $this->rollback(); - return false; - - } - - if ($this->recount_messages($this->peer_name_id,$this->peer_server_id,$this->tslice) === true) { - - $stats = $this->result->cnt; - - } - else { - - $this->rollback(); - return false; - } - - if ($this->if_chat_exist($this->peer_name_id,$this->peer_server_id,$this->tslice) === true) { - - - if ($this->result->cnt == 1) { - - if ($this->update_stats($this->peer_name_id,$this->peer_server_id,$this->tslice,$stats) === false) { - - $this->rollback(); - return false; - } - - } - else { - - if ($this->insert_stats($this->peer_name_id,$this->peer_server_id,$this->tslice,$stats) === false) { - - $this->rollback(); - return false; - - } - } - - } - else{ - - $this->rollback(); - return false; - } - - if ($this->move_mylink_from_trash($peer_name_id,$link) === false) { - - $this->rollback(); - return false; - - } - - if ($this->move_fav_from_trash($peer_name_id,$peer_server_id,$tslice) === false) { - - $this->rollback(); - return false; - } - - $this->commit(); - return true; - - - } - - private function if_chat_exist($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q044"; - $query="SELECT - 1 as cnt - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id = '".$this->user_id."' - AND - peer_name_id='$peer_name_id' - AND - peer_server_id='$peer_server_id' - AND - at = '$tslice' - - "; - - return $this->select($query); - - } - - private function insert_stats($peer_name_id,$peer_server_id,$tslice,$stats) { - - $this->id_query = "Q045"; - $query="INSERT INTO - `logdb_stats_".$this->xmpp_host."` (owner_id,peer_name_id,peer_server_id,at,count) - VALUES - ( - '".$this->user_id."', - '$peer_name_id', - '$peer_server_id', - '$tslice', - '$stats - ') - - "; - - return $this->insert($query); - } - - private function update_stats($peer_name_id,$peer_server_id,$tslice,$stats) { - - $this->id_query = "Q046"; - $query="UPDATE - `logdb_stats_".$this->xmpp_host."` - SET - count='$stats' - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='$peer_name_id' - AND - peer_server_id='$peer_server_id' - AND - at='$tslice' - - "; - - return $this->update($query); - } - - private function recount_messages($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q047"; - $table = $this->construct_table($tslice); - $query="SELECT - count(timestamp) as cnt - FROM - `$table` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='$peer_name_id' - AND - peer_server_id='$peer_server_id' - AND - ext is NULL - "; - - return $this->select($query); - - } - - private function move_mylink_from_trash($peer_name_id,$link) { - - $this->id_query = "Q048"; - $lnk = $this->sql_validate($link,"string"); - $query="UPDATE - jorge_mylinks - SET - ext = NULL - WHERE - owner_id ='".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - peer_name_id='$peer_name_id' - AND - ext = '".$this->ext_idx."' - AND - link like '$link%' - "; - - return $this->update($query); - - } - - private function move_fav_from_trash($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q049"; - $query="UPDATE - jorge_favorites - SET - ext = NULL - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='$peer_name_id' - AND - peer_server_id='$peer_server_id' - AND - tslice='$tslice' - AND - ext = '".$this->ext_idx."' - AND - vhost='".$this->vhost."' - "; - - return $this->update($query); - - } - - public function delete_messages($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q050"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $table = $this->construct_table($this->tslice,"date"); - $query="DELETE FROM - `$table` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - ext = '".$this->ext_idx."' - - "; - - return $this->delete($query); - - } - - public function delete_mylinks($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q051"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $query="DELETE FROM - jorge_mylinks - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - ext='".$this->ext_idx."' - AND - peer_name_id = '".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - datat = '".$this->tslice."' - - "; - - return $this->delete($query); - - } - - public function delete_favorites($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q052"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $query="DELETE FROM - jorge_favorites - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - tslice='".$this->tslice."' - AND - ext = '".$this->ext_idx."' - AND - vhost='".$this->vhost."' - "; - - return $this->delete($query); - - } - - public function search_query($tslice) { - - $this->id_query = "Q053"; - $this->vital_check(); - if ($this->user_query === null) { - - return false; - - } - $table = $this->construct_table($this->sql_validate($tslice,"date")); - $query="SELECT - timestamp AS ts, - peer_name_id, - peer_server_id, - direction, - ext, - body, - MATCH(body) AGAINST('".$this->user_query."' IN BOOLEAN MODE) AS score - FROM - `$table` - FORCE INDEX - (search_i) - WHERE - MATCH(body) AGAINST('".$this->user_query."' IN BOOLEAN MODE) - AND - owner_id='".$this->user_id."' - LIMIT - 0,10000 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("ts","peer_name_id","peer_server_id","direction","ext","body","score")); - - } - - public function search_query_chat_stream($peer_name_id,$peer_server_id,$tslice,$start_tag = null) { - - $this->id_query = "Q054"; - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $table = $this->construct_table($this->sql_validate($this->tslice,"date")); - if ($start_tag === null) { - - $start_tag="0"; - } - $start_tag = $this->sql_validate($start_tag,"integer"); - - $query="SELECT - from_unixtime(timestamp+0) AS ts, - peer_name_id, - peer_server_id, - direction, - ext, - body - FROM - `$table` - FORCE INDEX - (search_i) - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - LIMIT - $start_tag,10000 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("ts","peer_name_id","peer_server_id","direction","ext","body")); - - } - - public function search_query_in_user_chat($peer_name_id,$peer_server_id,$tslice,$start_tag) { - - $this->id_query = "Q055"; - if ($this->user_query === null) { - - return false; - - } - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $table = $this->construct_table($this->sql_validate($this->tslice,"date")); - if ($start_tag === null) { - - $start_tag="0"; - } - $start_tag = $this->sql_validate($start_tag,"integer"); - $query="SELECT - timestamp AS ts, - peer_name_id, - peer_server_id, - direction, - ext, - body , - MATCH(body) AGAINST('".$this->user_query."' IN BOOLEAN MODE) AS score - FROM - `$table` - FORCE INDEX - (search_i) - WHERE - match(body) against('".$this->user_query."' IN BOOLEAN MODE) - AND - owner_id='".$this->user_id."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - LIMIT - $start_tag,10000 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("ts","peer_name_id","peer_server_id","direction","ext","body","score")); - - } - - public function create_search_results_table() { - - $this->id_query = "Q055"; - $this->query_type = "create_table"; - $query="CREATE TEMPORARY TABLE - jorge_results_table - ( - ts VARCHAR(30), - time_slice VARCHAR(10), - peer_name_id MEDIUMINT, - peer_server_id SMALLINT, - direction ENUM('to','from'), - body TEXT, - score FLOAT, - ext TINYINT - ) - "; - - return $this->db_query($query); - } - - public function insert_data_to_result_table($ts,$time_slice,$peer_name_id,$peer_server_id,$direction,$body,$score,$ext){ - - $this->id_query = "Q056"; - $query="INSERT INTO jorge_results_table - (ts,time_slice,peer_name_id,peer_server_id,direction,body,score,ext) - VALUES ( - '$ts', - '$time_slice', - '$peer_name_id', - '$peer_server_id', - '$direction', - '$body', - '$score', - '$ext' - ) - "; - - return $this->insert($query); - - } - - public function get_search_results() { - - $this->id_query = "Q057"; - $query="SELECT - FROM_UNIXTIME(ts+0) AS ts, - time_slice, - peer_name_id, - peer_server_id, - direction, - body, - score, - ext - FROM - jorge_results_table - ORDER BY - score - DESC LIMIT 100 - - "; - - $this->select($query,"raw"); - return $this->commit_select(array("ts","time_slice","peer_name_id","peer_server_id","direction","body","score","ext")); - - } - - public function get_folder_content($at) { - - $this->id_query = "Q058"; - $this->vital_check(); - $at = $this->sql_validate($at,"string"); - if ($this->spec_ignore === true) { - - $sql = "AND peer_name_id != '".$this->ignore_id."'"; - - } - $query="SELECT - distinct(at) AS at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id = '".$this->user_id."' - AND - substring(at,1,7) = '$at' - $sql - ORDER BY - str_to_date(at,'%Y-%m-%d') - DESC - "; - - $this->select($query,"raw"); - return $this->commit_select(array("at")); - - } - - public function insert_user_id($user_name) { - - $this->id_query = "Q059"; - $user_name = $this->sql_validate($user_name,"string"); - $query="INSERT INTO - `logdb_users_".$this->xmpp_host."` - SET - username='$user_name' - "; - return $this->insert($query); - - } - - public function insert_new_settings($user_name) { - - $this->id_query = "Q060"; - $user_name = $this->sql_validate($user_name,"string"); - $query="INSERT INTO - `logdb_settings_".$this->xmpp_host."` (owner_id,dolog_default) - VALUES - ((SELECT user_id FROM `logdb_users_".$this->xmpp_host."` WHERE username='$user_name'), '1') - - "; - return $this->insert($query); - - } - - public function get_jorge_pref($pref_id = null) { - - $this->id_query = "Q061"; - if ($pref_id !== null) { - - $pref_id = $this->sql_validate($pref_id,"integer"); - $sql = "AND pref_id = '$pref_id'"; - - } - $query="SELECT - pref_id, - pref_value - FROM - jorge_pref - WHERE - owner_id='".$this->user_id."' - $sql - AND - vhost = '".$this->vhost."' - "; - - if ($pref_id === null) { - - $this->select($query,"raw"); - return $this->commit_select(array("pref_id","pref_value")); - - } - else{ - - return $this->select($query); - - } - - return false; - - } - - public function set_jorge_pref($pref_id,$pref_value) { - - $this->id_query = "Q062"; - $this->vital_check(); - $pref_id = $this->sql_validate($pref_id,"integer"); - $pref_value = $this->sql_validate($pref_value,"integer"); - if ($this->row_count("SELECT pref_id FROM jorge_pref WHERE owner_id='".$this->user_id."' AND pref_id='$pref_id' AND vhost='".$this->vhost."'") === false) { - - return false; - - } - if ($this->result > 0) { - - $query="UPDATE - jorge_pref - SET - pref_value='$pref_value' - WHERE - owner_id='".$this->user_id."' - AND - pref_id='$pref_id' - AND - vhost = '".$this->vhost."' - "; - return $this->update($query); - - } - else{ - - $query="INSERT INTO - jorge_pref(owner_id,pref_id,pref_value,vhost) - VALUES - ('".$this->user_id."','$pref_id','$pref_value','".$this->vhost."') - "; - return $this->insert($query); - - } - - return false; - - } - - public function sphinx_get_single($peer_name_id, $peer_server_id, $peer_resource_id, $timestamp, $tslice) { - - $this->id_query = "Q063"; - $this->vital_check(); - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $peer_resource_id = $this->sql_validate($peer_resource_id,"integer"); - $timestamp = $this->sql_validate($timestamp,"string"); - $query="SELECT - body - FROM - `".$this->construct_table($this->tslice)."` - WHERE - owner_id = '".$this->user_id."' - AND - peer_name_id = '".$this->peer_name_id."' - AND - peer_server_id = '".$this->peer_server_id."' - AND - peer_resource_id = '".$peer_resource_id."' - AND - timestamp like '".$timestamp."%' - - "; - - return $this->select($query); - - } - - public function get_favorites() { - - $this->id_query = "Q064"; - $this->vital_check(); - $query="SELECT * - FROM - jorge_favorites - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - ext is NULL - ORDER BY - str_to_date(tslice,'%Y-%m-%d') - DESC - "; - - $this->select($query,"raw"); - return $this->commit_select(array("link_id","peer_name_id","peer_server_id","resource_id","tslice","comment")); - - } - - public function set_favorites($peer_name_id,$peer_server_id,$peer_resource_id = null, $tslice,$comment) { - - $this->id_query = "Q065"; - $this->vital_check(); - $this->prepare($peer_name_id,$peer_server_id,$tslice); - #$peer_resource_id = $this->sql_validate($peer_resource_id,"integer"); - $comment = $this->sql_validate($comment,"string"); - $query="INSERT INTO - jorge_favorites(owner_id,peer_name_id,peer_server_id,tslice,comment,vhost) - VALUES( - '".$this->user_id."', - '".$this->peer_name_id."', - '".$this->peer_server_id."', - '".$this->tslice."', - '$comment', - '".$this->vhost."' - ) - "; - - return $this->insert($query); - - } - - public function delete_favorites_id($link_id) { - - $this->id_query = "Q066"; - $this->vital_check(); - $link_id = $this->sql_validate($link_id,"string"); - $query="DELETE FROM - jorge_favorites - WHERE - owner_id = ".$this->user_id." - AND - vhost='".$this->vhost."' - AND - link_id = '$link_id'; - "; - - return $this->delete($query); - - } - - public function check_favorite($peer_name_id,$peer_server_id,$tslice) { - - $this->id_query = "Q067"; - $this->vital_check(); - $this->prepare($peer_name_id,$peer_server_id,$tslice); - $query="SELECT - count(*) as cnt - FROM - jorge_favorites - WHERE - owner_id='".$this->user_id."' - AND - tslice='".$this->tslice."' - AND - peer_name_id='".$this->peer_name_id."' - AND - peer_server_id='".$this->peer_server_id."' - AND - vhost='".$this->vhost."' - AND - ext is null - "; - - return $this->select($query); - - } - - public function get_favorites_count() { - - $this->id_query = "Q068"; - $this->vital_check(); - $query="SELECT - count(*) as cnt - FROM - jorge_favorites - WHERE - owner_id = '".$this->user_id."' - AND - vhost='".$this->vhost."' - AND - ext is null - "; - - return $this->select($query); - - } - - public function get_top_ten($date,$vhost = null) { - - $this->id_query = "Q069"; - if ($vhost === null) { - - $vh = $this->xmpp_host; - - } - else{ - - $vh = $this->vh($vhost,true); - - } - $date = $this->sql_validate($date,"date"); - $query="SELECT - at, - owner_id, - peer_name_id, - peer_server_id, - count - FROM - `logdb_stats_".$vh."` - WHERE - at = '$date' - ORDER BY - count - DESC LIMIT 10 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("at","owner_id","peer_name_id","peer_server_id","count")); - - } - - public function get_monthly_stats($vhost = null) { - - $this->id_query = "Q070"; - if ($vhost === null) { - - $vh = $this->xmpp_host; - - } - else{ - - $vh = $this->vh($vhost,true); - - } - // This query need tweak to use ex.: where at between '2009-2' and '2009-3', it speeds up and corrects query, also forces to use index, instead full table scan - $query="SELECT - count(distinct(owner_id)) AS users_total, - unix_timestamp(at)*10000 AS time_unix, - sum(count) AS messages - FROM - `logdb_stats_".$vh."` - GROUP BY - at - ORDER BY - str_to_date(at,'%Y-%m-%d') - DESC LIMIT 30 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("users_total","time_unix","messages")); - - } - - public function get_hourly_stats($date,$vhost = null) { - - $this->id_query = "Q071"; - if ($vhost === null) { - - $vh = $this->vhost; - - } - else{ - - $vh = $this->vh($vhost); - - } - $date = $this->sql_validate($date,"date"); - $query="SELECT - hour, - value - FROM - jorge_stats - WHERE - day='$date' - AND - vhost='".$vh."' - ORDER BY - hour - ASC - "; - - $this->select($query,"raw"); - return $this->commit_select(array("hour","value")); - - } - - public function get_weekly_stats($date_start,$date_end,$vhost = null) { - - $this->id_query = "Q072"; - if ($vhost === null) { - - $vh = $this->vhost; - - } - else{ - - $vh = $this->sql_validate($vhost,"string"); - - } - $date_start = $this->sql_validate($date_start,"date"); - $date_end = $this->sql_validate($date_end,"date"); - $query="SELECT - hour, - value - FROM - jorge_stats - WHERE - day<='$date_end' - AND - day >= '$date_start' - AND - vhost='".$vh."' - ORDER BY - day,hour - ASC - "; - - $this->select($query,"raw"); - return $this->commit_select(array("hour","value")); - - } - - public function get_personal_top() { - - $this->id_query = "Q073"; - $this->vital_check(); - $query="SELECT - peer_name_id, - peer_server_id, - at, - count - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id!='".$this->ignore_id."' - AND - ext is NULL - ORDER BY - count - DESC LIMIT 10 - "; - - $this->select($query,"raw"); - return $this->commit_select(array("peer_name_id","peer_server_id","at","count")); - - } - - public function get_personal_sum() { - - $this->id_query = "Q074"; - $this->vital_check(); - $query="SELECT - sum(count) as cnt - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id!='".$this->ignore_id."' - "; - return $this->select($query); - - } - - public function erase_all() { - - $this->id_query = "Q075"; - $this->vital_check(); - $query="SELECT - distinct(at) - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - "; - $this->select($query,"raw"); - $this->commit_select(array("at")); - $results = $this->result; - $this->id_query = "Q076"; - foreach ($results as $result) { - - $query="DELETE FROM - `logdb_messages_$result[at]_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - "; - if ($this->delete($query) === false) { - - return false; - - } - - } - $this->id_query = "Q077"; - $query="DELETE FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - "; - if ($this->delete($query) === false) { - - return false; - - } - if ($this->jorge_cleanup_soft() === false) { - - return false; - - } - - return true; - - } - - public function jorge_cleanup() { - - $this->id_query = "Q081"; - $this->vital_check(); - $query="DELETE FROM - jorge_pref - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - "; - if ($this->delete($query) === false) { - - return false; - - } - $this->id_query = "Q082"; - $query="DELETE FROM - `logdb_settings_".$this->xmpp_host."` - where - owner_id='".$this->user_id."' - "; - if ($this->delete($query) === false) { - - return false; - - } - - return true; - - } - - public function jorge_cleanup_soft() { - - $this->id_query = "Q083"; - $this->vital_check(); - $query="DELETE FROM - jorge_mylinks - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - "; - if ($this->delete($query) === false) { - - return false; - - } - $this->id_query = "Q084"; - $query="DELETE FROM - jorge_favorites - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - "; - if ($this->delete($query) === false) { - - return false; - - } - $this->id_query = "Q085"; - $query="DELETE FROM - pending_del - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - "; - if ($this->delete($query) === false) { - - return false; - - } - - return true; - - } - - public function get_next_prev_day($peer_name_id, $peer_server_id, $tslice, $np) { - - $this->id_query = "Q086"; - $this->vital_check(); - $this->prepare($peer_name_id,$peer_server_id,$tslice); - if ($np === "n") { - - $sql1 = ">"; - $sql2 = "ASC"; - } - elseif($np === "p") { - - $sql1 = "<"; - $sql2 = "DESC"; - } - else{ - - return false; - - } - $query="SELECT - at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - peer_name_id = '".$this->peer_name_id."' - AND - peer_server_id = '".$this->peer_server_id."' - AND - str_to_date(at, '%Y-%m-%d') $sql1 str_to_date('".$this->tslice."', '%Y-%m-%d') - ORDER BY - str_to_date(at,'%Y-%m-%d') - $sql2 LIMIT 1 - "; - - return $this->select($query); - - } - - public function get_last_day() { - - $this->id_query = "Q087"; - $this->vital_check(); - if ($this->spec_ignore === true) { - - $sql = "AND peer_name_id != '".$this->ignore_id."'"; - - } - - $query="SELECT - at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id = '".$this->user_id."' - $sql - ORDER BY str_to_date(at,'%Y-%m-%d') DESC LIMIT 1 - "; - - return $this->select($query); - - } - - private function get_ignore_id() { - - $this->id_query = "Q088"; - $query="SELECT - user_id AS ignore_id - FROM - `logdb_users_".$this->xmpp_host."` - WHERE - username='' - "; - - return $this->select($query); - - } - - private function set_ignore_id() { - - if ($this->get_ignore_id() === false) { - - return false; - - } - else{ - - $this->ignore_id = $this->result->ignore_id; - return true; - - } - - } - - private function get_ext_index($table) { - - $this->id_query = "Q089"; - $query="SELECT - ext+1 as idx - FROM - `".$table."` - WHERE - owner_id = '".$this->user_id."' - AND - peer_name_id = '".$this->peer_name_id."' - AND - peer_server_id = '".$this->peer_server_id."' - AND - ext is not NULL - ORDER BY - ext - DESC LIMIT 1 - "; - - return $this->select($query); - - } - - public function get_last_attempt($user_id) { - - $this->id_query = "Q090"; - $user_id = $this->sql_validate($user_id,"integer"); - $query="SELECT - count(id_user) AS cnt - FROM - jorge_logger - WHERE - id_user = '$user_id' - AND - log_time > date_sub(now(),interval 1 minute) - "; - - return $this->select($query); - - } - - public function is_left_or_right($date) { - - $this->id_query = "Q091"; - $query="SELECT - at - FROM - `logdb_stats_".$this->xmpp_host."` - WHERE - owner_id='".$this->user_id."' - AND - at like '$date%' - LIMIT 1 - "; - - return $this->row_count($query); - - } - - public function set_own_name($own_name) { - - $this->id_query = "Q092"; - $this->vital_check(); - $own_name = $this->sql_validate($own_name,"string"); - $query="REPLACE INTO - jorge_self_names (owner_id, own_name, vhost) - VALUES - ( - '".$this->user_id."', - '".$own_name."', - '".$this->vhost."' - ) - "; - - return $this->replace_q($query); - - } - - public function get_own_name() { - - $this->id_query = "Q093"; - $this->vital_check(); - $query="SELECT - own_name - FROM - jorge_self_names - WHERE - owner_id='".$this->user_id."' - AND - vhost='".$this->vhost."' - "; - - return $this->select($query); - - } - - public function set_ext_index($idx) { - - /* - This is bit messy as we use ctype_digit() to check if string is an integer, - so any number need to be set as type string and then pass to sql_validate() for validation. - This should be changed in sql_validate() function to take care of all data that it gets... - */ - - settype($idx,"string"); - if ($this->sql_validate($idx,"integer") === false) { - - return false; - - } - else{ - - $this->ext_idx = $idx; - return true; - - } - - return false; - - } - - public function get_last_idx() { - - return $this->ext_idx; - - } - - public function set_user_query($user_query) { - - $this->user_query = $this->sql_validate($user_query,"string"); - return true; - - } - - public function remove_messages_from_trash($peer_name_id,$peer_server_id,$tslice) { - - if ($this->delete_messages($peer_name_id,$peer_server_id,$tslice) === true) { - - $this->unset_undo_table($peer_name_id,$peer_server_id,$tslice); - $this->delete_mylinks($peer_name_id,$peer_server_id,$tslice); - $this->delete_favorites($peer_name_id,$peer_server_id,$tslice); - - } - - else{ - - return false; - - } - - return true; - - } - - public function db_error() { - - return $this->is_error; - - } - - public function set_user_id($user_id) { - - $user_id = $this->sql_validate($user_id,"integer"); - if ($user_id === false) { - - return false; - - } - else { - - $this->user_id = $user_id; - return true; - } - - return false; - - - } - - protected function sql_validate($val,$type) { - - if($this->db_driver === "mysql") { - - if ($type==="integer") { - - // Default - all this "integer" strings are really characters with should be numeric. Need Test! - settype($val,"string"); - - if(ctype_digit($val)) { - - return $val; - - } - else{ - $this->is_error = true; - return false; - } - } - elseif($type==="string") { - - return mysql_escape_string($val); - - } - - elseif($type==="date") { - - list($ye, $mo, $da) = split("-", $val); - if (!ctype_digit($ye) || !ctype_digit($mo) || !ctype_digit($da)) { - - $this->is_error = true; - return false; - - } - else { - - return $val; - - } - - $this->is_error = true; - return false; - } - else{ - $this->is_error = true; - return false; - } - - - } - - return false; - - } - - private function commit_select($arr) { - - if ($this->is_error === true) { - - return false; - - } - - $this->object_to_array($arr); - return true; - - } - - private function object_to_array($arr) { - - settype($i, "integer"); - settype($z, "integer"); - $result = $this->result; - while($row = mysql_fetch_object($result)) { - - $i++; - foreach ($arr as $key) { - - $z++; - $items[$i][$key] = $row->$key; - - } - - - } - - return $this->result = $items; - - } - - private function prepare($peer_name_id = null,$peer_server_id = null, $tslice = null) { - - if ($peer_name_id !== null) { - - $this->peer_name_id = $this->sql_validate($peer_name_id,"integer"); - - } - - if ($peer_server_id !== null) { - - $this->peer_server_id = $this->sql_validate($peer_server_id,"integer"); - - } - - if ($tslice !== null) { - - $this->tslice = $this->sql_validate($tslice,"date"); - - } - - $this->vital_check(); - return; - - } - - private function construct_table($tslice) { - - return $tslice_table = $this->messages_table.''.$tslice.'_'.$this->xmpp_host; - - } - - private function vital_check() { - - if($this->user_id === false OR !$this->user_id) { - - print "

Operation aborted! Can't continue.

"; - exit; // abort all, user_id MUST be set. - } - return true; - - } - - private function vh($vhost,$dash = null) { - - if ($dash === true) { - - return str_replace(".","_",$this->sql_validate($vhost,"string")); - - - } - else{ - - return $this->sql_validate($vhost,"string"); - - } - - } - - public function set_debug($bool) { - - if($bool === true) { - - $this->is_debug = true; - return true; - - } - elseif($bool === false) { - - $this->is_debug = false; - return true; - - } - - return false; - - } - - public function spec_ignore($bool) { - - if($bool === true) { - - $this->spec_ignore = true; - return true; - - } - elseif($bool === false) { - - $this->spec_ignore = false; - return true; - - } - - return false; - - } - - private function show_debug_info($query = null, $time = null) { - - if ($this->is_debug === true) { - - if ($query !== null) { - - print "
QueryID: ".$this->id_query.": ".htmlspecialchars($query)."
"; - } - if ($query === null AND $time !== null) { - - print "SQL performed in: ".$this->time_result."


"; - - } - - } - } - - private function sql_time() { - - list($usec, $sec) = explode(" ",microtime()); - return ((float)$usec + (float)$sec); - } - - private function time_start() { - - if ($this->is_debug === true) { - - return $this->time_start = $this->sql_time(); - - } - - } - - private function time_end() { - - if ($this->is_debug === true) { - - $start = $this->time_start; - $end = $this->sql_time(); - return $this->time_result = substr($end - $start, 0, 10); - - } - - } - - public function __destruct() { - - mysql_free_result(); - mysql_close(); - $this->user_id = null; - $this->result = null; - - } - -} - -?> diff --git a/jorge/class.ejabberd_xmlrpc.php b/jorge/class.ejabberd_xmlrpc.php deleted file mode 100644 index 2055921..0000000 --- a/jorge/class.ejabberd_xmlrpc.php +++ /dev/null @@ -1,257 +0,0 @@ -set_user("username","password","optional-new_password"); - -this is usefull especialy for scripts like bulk account creation/deletion etc... - -Method: Returned values: -crete_account() true|false|exist -delete_account() true|false -auth() true|false -check_account() true|flase -change_password() true|false -get_roster() Array() -test_rpc() String - -Example of authentication: - -try { - if($ejabberd_rpc->auth() === true) { - - print "Auth OK"; - } - else { - print "Unknown account or bad password"; - } -} -catch(Exception $e) { - echo "Exception: ".$e->getMessage(); - echo ", Code: ".$e->getCode(); -} - -*/################################################## - -class rpc_connector { - - protected $rpc_server; - protected $rpc_port; - protected $username; - protected $password; - protected $newpass; - protected $vhost; - protected $parms; - protected $method; - - public function __construct($rpc_server,$rpc_port,$vhost,$username = null,$password = null,$newpass = null) { - $this->setData($rpc_server,$rpc_port,$vhost,$username,$password,$newpass); - } - - - protected function setData($rpc_server, $rpc_port, $vhost, $username, $password,$newpass) { - $this->rpc_server = $rpc_server; - $this->rpc_port = $rpc_port; - $this->vhost = $vhost; - $this->username = $username; - $this->password = $this->clean_password($password); - $this->newpass = $this->clean_password($newpass); - } - - public function set_user($username,$password,$newpass = null) { - - $this->username = $username; - $this->password = $this->clean_password($password); - $this->newpass = $this->clean_password($newpass); - - } - - protected function commit_rpc() { - - $request = xmlrpc_encode_request($this->method,$this->parms); - $context = stream_context_create(array('http' => array( - 'method' => "POST", - 'header' => "Content-Type: text/xml; charset=utf-8\r\n" . - "User-Agent: XMLRPC::Client JorgeRPCclient", - 'content' => $request - ))); - - $file = file_get_contents("http://$this->rpc_server".":"."$this->rpc_port", false, $context); - $response = xmlrpc_decode($file,"utf8"); - if (xmlrpc_is_fault($response)) { - - throw new Exception("XML-RPC Call Failed. Unrecoverable condition",0); - - } else { - - return $response; - } - - } - - protected function is_value($value) { - - if($value === null) { - return false; - } - elseif($value==""){ - return false; - } - else{ - return true; - } - - - } - - protected function clean_password($password) { - - if (get_magic_quotes_gpc() === 1) { - return stripslashes($password); - } - - return $password; - } - - public function auth() { - - $this->method = "check_password"; - $this->parms = array("user"=>"$this->username","host"=>"$this->vhost","password"=>"$this->password"); - if ($this->commit_rpc() === 0 ) { - - return true; - - } - else{ - - return false; - - } - - - } - - public function create_account() { - - if ($this->is_value($this->username) === false OR $this->is_value($this->password) === false) { return false; } - $this->method = "create_account"; - $this->parms = array("user"=>"$this->username","host"=>"$this->vhost","password"=>"$this->password"); - $call = $this->commit_rpc(); - if ($call === 0) { - - return true; - } - elseif($call === 409) { - return "exist"; - } - elseif($call === 1) { - return false; - } - - } - - public function check_account() { - - if ($this->is_value($this->username) === false) { return false; } - $this->method = "check_account"; - $this->parms = array("user"=>"$this->username","host"=>"$this->vhost"); - if ($this->commit_rpc() === 1) { - - return false; - - } - else{ - - return true; - - } - - } - - public function change_password() { - - if ($this->is_value($this->newpass) === false OR $this->is_value($this->username) === false) { return false; } - $this->method = "change_password"; - $this->parms = array("user"=>"$this->username","host"=>"$this->vhost","newpass"=>"$this->newpass"); - - if ($this->commit_rpc() === 0) { - - $this->password = $this->newpass; - return true; - - } - else{ - return false; - - } - - } - - public function get_roster() { - - $this->method = "get_roster"; - $this->parms = array("user"=>"$this->username","server"=>"$this->vhost"); - return $this->commit_rpc(); - } - - public function delete_account() { - - if ($this->is_value($this->password) === false OR $this->is_value($this->username) === false) { return false; } - $this->method = "delete_account"; - $this->parms = array("user"=>"$this->username","host"=>"$this->vhost","password"=>"$this->password"); - $this->commit_rpc(); - if ($this->check_account() === false) { - - return true; - - } - else { - - return false; - } - } - - public function online_users() { - - $this->method = "online_users"; - $this->parms = "null"; - return $this->commit_rpc(); - } - - public function test_rpc() { - - $this->method = "echothis"; - $this->parms = "If you can read this then RPC is working..."; - return $this->commit_rpc(); - - } - - -} - -?> diff --git a/jorge/class.helper.php b/jorge/class.helper.php deleted file mode 100644 index 0aa85bf..0000000 --- a/jorge/class.helper.php +++ /dev/null @@ -1,358 +0,0 @@ -td = $td; - - } - - public function __destruct() { - - mcrypt_generic_deinit($this->td); - mcrypt_module_close($this->td); - - } - - public function crypt_url($url) { - - return str_replace("+", "kezyt2s0", $this->url_encrypt($url)); - } - - public function decrypt_url($url) { - - $url = str_replace("kezyt2s0", "+",$url); - return $this->decode_string($this->url_decrypt(base64_decode($url))); - - } - - private function url_encrypt($url) { - - $prepared_string = "begin&".$url; - $integrity = md5($prepared_string); - $url = "integrity=$integrity&".$prepared_string; - $td = $this->td; - $c_t = mcrypt_generic($td, $url); - return base64_encode($c_t); - - } - - private function url_decrypt($url) { - - $td = $this->td; - $p_t = mdecrypt_generic($td, $url); - return trim($p_t); - - } - -} - - -Class parser { - - public $tslice = null; - public $peer_name_id = null; - public $peer_name = null; - public $peer_server_id = null; - public $peer_server = null; - public $jid = null; - public $ismylink = null; - public $linktag = null; - public $strt = null; - public $lnk = null; - public $action = null; - public $search_phase = null; - public $offset_arch = null; - public $offset_day = null; - public $tag_count = null; - public $time_start = null; - public $time_end = null; - public $single = null; - - - protected function decode_string($url) { - - parse_str($url); - $reconstructed = strstr($url,"begin"); - settype($integrity,"string"); - if ($integrity === md5($reconstructed)) { - - if (isset($tslice)) { - $this->tslice = $tslice; - } - if (isset($peer_name_id)) { - $this->peer_name_id = $peer_name_id; - } - if (isset($peer_server_id)) { - $this->peer_server_id = $peer_server_id; - } - if (isset($jid)) { - $this->jid = $jid; - } - if (isset($lnk)) { - $this->lnk = $lnk; - } - if (isset($ismylink)) { - $this->ismylink = $ismylink; - } - if (isset($linktag)) { - $this->linktag = $linktag; - } - if (isset($strt)) { - $this->strt = $strt; - } - if (isset($action)) { - $this->action = $action; - } - if (isset($peer_name)) { - $this->peer_name = $peer_name; - } - if (isset($peer_server)) { - $this->peer_server = $peer_server; - } - if (isset($search_phase)) { - $this->search_phase = $search_phase; - } - if (isset($offset_arch)) { - $this->offset_arch = $offset_arch; - } - if (isset($offset_day)) { - $this->offset_day = $offset_day; - } - if (isset($tag_count)) { - $this->tag_count = $tag_count; - } - if (isset($time_start)) { - $this->time_start = $time_start; - } - if (isset($time_end)) { - $this->time_end = $time_end; - } - if (isset($single)) { - $this->single = $single; - } - - return true; - - } - else { - - return false; - - } - - return false; - } - - -} - -Class render_html { - - protected $html_head = array(); - protected $html_menu = array(); - protected $html_over; - protected $html_main = array(); - protected $html_body = array(); - protected $html_foot = array(); - private $head_items = integer; - private $menu_items = integer; - private $main_items = integer; - private $body_items = integer; - private $foot_itesm = integer; - - public function system_message($html) { - - $this->html_main = array("sys_message"=>$this->render_system($html)); - return; - - } - - public function status_message($html) { - - $this->html_main = array("status_message"=>$this->render_status($html)); - return; - - } - - public function alert_message($html) { - - $this->html_main = array("alert_message"=>$this->render_alert($html)); - return; - - } - - public function headers($html) { - - if ($this->head_items === 0) { - - $this->html_head = array("0"=>$html); - $this->head_items = 1; - - } - else{ - - $this->head_items = $this->head_items + 1; - $this->html_head = $this->html_head += array($this->head_items=>$html); - - } - return; - - } - - public function menu($html) { - - if ($this->menu_items === 0) { - - $this->html_menu = array("0"=>$html); - $this->menu_items = 1; - - } - else{ - - $this->menu_items = $this->menu_items + 1; - $this->html_menu = $this->html_menu += array($this->menu_items=>$html); - } - return; - - } - - public function set_overview($html) { - - $this->html_over = $html; - return; - - } - - public function set_body($html) { - - if ($this->body_items === 0) { - - $this->html_body = array("0"=>$html); - $this->body_items = 1; - - } - else{ - - $this->body_items = $this->body_items + 1; - $this->html_body = $this->html_body += array($this->body_items=>$html); - } - return; - - } - - public function foot($html) { - - if ($this->foot_items === 0) { - - $this->html_foot = array("0"=>$html); - $this->foot_items = 1; - } - else{ - - $this->foot_items = $this->foot_items + 1; - $this->html_foot = $this->html_foot += array($this->foot_items=>$html); - } - return; - - } - - public function commit_render() { - - $html_head = $this->html_head; - $html_menu = $this->html_menu; - $html_over = $this->html_over; - $html_main = $this->html_main; - $html_body = $this->html_body; - $html_foot = $this->html_foot; - - for ($z=0;$z<=$this->head_items;$z++) { - - $out .= $html_head[$z]; - - } - $out .= $html_main[sys_message]; - for ($z=0;$z<=$this->menu_items;$z++) { - - $out .= $html_menu[$z]; - - } - $out .= $html_over; - $out .= $html_main[alert_message]; - $out .= $html_main[status_message]; - for ($z=0;$z<=$this->body_items;$z++) { - - $out .= $html_body[$z]; - - } - for ($z=0;$z<=$this->foot_items;$z++) { - - $out .= $html_foot[$z]; - - } - echo $out; - return; - - } - - public function destroy_content() { - - $this->html_body = array(); - return; - - } - - protected function render_alert($message, $class = "message") { - - - return '
'.$message.'

'; - - } - - protected function render_status($message, $class = "message") { - - return '
'.$message.'

'; - - } - - protected function render_system($message, $class = null) { - - return '
'.$message.'

'; - - } - - -} - -?> diff --git a/jorge/class.roster.php b/jorge/class.roster.php deleted file mode 100644 index beb0c91..0000000 --- a/jorge/class.roster.php +++ /dev/null @@ -1,147 +0,0 @@ -$nick,"group"=>$group); - if ($this->roster) { - - $this->roster = $this->roster += $new_item; - - } - else { - - $this->roster = $new_item; - - } - - } - - public function get_roster() { - - return $this->roster; - - } - - public function get_nick($jid) { - - $roster = $this->roster; - $nick = $roster[$jid][nick]; - return htmlspecialchars($nick); - - } - - public function get_group($jid) { - - $roster = $this->roster; - $group = $roster[$jid][group]; - return htmlspecialchars($group); - } - - public function get_nick_group($jid) { - - $roster = $this->roster; - $result = array($roster[$jid][nick],$roster[$jid][group]); - return $result; - - } - - public function sort_by_jid($dir) { - - $arr = $this->roster; - if ($dir==="az") { - ksort($arr); - } - - elseif($dir==="za") { - krsort($arr); - } - else{ - return false; - } - - $this->roster = $arr; - - } - - public function sort_by_nick($dir) { - - $this->sort_roster($dir,"nick"); - } - - - public function sort_by_group($dir) { - - $this->sort_roster($dir,"group"); - - } - - public function sort_by_nick_group() { - - $arr = $this->roster; - array_multisort($this->prepare_multisort("group"),SORT_ASC, $this->prepare_multisort("nick"),SORT_ASC,$arr); - $this->roster = $arr; - } - - protected function sort_roster($dir,$field) { - - $arr = $this->roster; - if ($dir ==="az") { - - array_multisort($this->prepare_multisort("$field"),SORT_ASC,$arr); - - } - elseif($dir==="za") { - - array_multisort($this->prepare_multisort("$field"),SORT_DESC,$arr); - - } - else{ - return false; - } - - $this->roster = $arr; - - } - - protected function prepare_multisort($val) { - $arr = $this->roster; - foreach ($arr as $key => $row) { - $field[$key] = $row[$val]; - } - $ret = array_map('strtolower', $field); - return $ret; - - } - -} - -?> diff --git a/jorge/class.sessions.php b/jorge/class.sessions.php deleted file mode 100644 index fbb3a6a..0000000 --- a/jorge/class.sessions.php +++ /dev/null @@ -1,68 +0,0 @@ -id(); - @session_unset(); - @session_destroy(); - } - -} -?> diff --git a/jorge/config.php.inc b/jorge/config.php.inc deleted file mode 100644 index 9e16e50..0000000 --- a/jorge/config.php.inc +++ /dev/null @@ -1,99 +0,0 @@ - array ("pol","1"), - "English"=> array("eng", "2") - - ); - -// Define default language. Should be the name from language_support array. -define(default_language, "English"); - -// vhost and RPC settings -// RPC port: -$rpc_port="4666"; - -// vhost settings, format "xmpp.server.com"=>array of RPC servers (WARNING! Do not mistake vhost and RPC servers as this is crutial for authentication!) -$vhosts = array( - - "jabber.example.com"=> - array("10.0.0.1","10.0.0.2"), - - "jabber.example.eu"=> - array("10.0.0.3","10.0.0.4") - - ); - -// array of admins for domain -$vhosts_admins = array( - - "jabber.example.com"=> array("admin1","admin2","admin3"), - "jabber.example.eu"=> array("admin10","admin20") - - ); - -// MySQL database where mod_logdb is running on: -define("MYSQL_USER", ""); // username -define("MYSQL_PASS", ""); // password -define("MYSQL_NAME",""); // db name -define("MYSQL_HOST", ""); // host ip - -// Since version 1.5 Jorge is using reCAPTCHA code. Before running Jorge please go to: http://recaptcha.net/ and setup your account and get private key and public key: -define("CAPTCHA_PRIVATE",""); -define("CAPTCHA_PUBLIC",""); - -// secret key for scrambling URLs. Put here some random data (32 chars): -define("ENC_KEY","PleaseChangeMe"); - -// Turn SSL redirection in PHP -define("SSL_REDIRECT", "false"); - -// number of chat lines in browser (default: 300) -$num_lines_bro = "300"; - -// number of search results (default: 100) -$num_search_results = "100"; - -// splitting line. Value in seconds. Default 900s = 15 minutes -$split_line="900"; - -// links -$links='jabster.pl     - poczta     - kalendarz     - dokumenty - '; - -// copyright -$copy = "jabster.pl © 2009"; - -// custom logo -$brand_logo = "logo_jabster.png"; - -?> diff --git a/jorge/contacts.php b/jorge/contacts.php deleted file mode 100644 index d6dc3e0..0000000 --- a/jorge/contacts.php +++ /dev/null @@ -1,191 +0,0 @@ -set_overview('

'.$con_head[$lang].'

'.$con_notice[$lang].''); - -if ($_POST) { - - while (array_keys($_POST)) { - - $jid = base64_decode(str_replace("kezyt2s0", "+", key($_POST))); - $val = array_shift($_POST); - - if ($val=="n") { - - $do_not_log_list .=$jid."\n"; - - } - - } - - if ($db->update_log_list($do_not_log_list) === true) { - - $html->status_message($con_saved[$lang]); - - } - else { - - $html->alert_message($oper_fail[$lang]); - } - -} - -// sorting options -$get_sort = $_GET['sort']; -$get_dir = $_GET['o']; - -// validate -if (!ctype_digit($get_sort) AND !ctype_digit($get_dir)) { unset($get_sort); unset($get_dir); } - -if ($get_dir === "1") { - - $dir = "za"; - $get_dir = "2"; - - } - elseif($get_dir === "2"){ - - $dir = "az"; - $get_dir = "1"; - - } - else{ - - $dir = "az"; - $get_dir = "2"; - - } - -if ($get_sort === "1") { - - $ejabberd_roster->sort_by_jid($dir); - - } - elseif($get_sort === "2") { - - $ejabberd_roster->sort_by_nick($dir); - - } - elseif($get_sort === "3") { - - $ejabberd_roster->sort_by_group($dir); - } - else{ - $ejabberd_roster->sort_by_nick_group(); - } - - -$roster_con = $ejabberd_roster->get_roster(); - -if ($roster_con) { - - $db->get_log_list(); - $do_notlog_list = $db->result; - - $html->set_body('
'); - - if ($get_sort) { - - $html->set_body(''); - - } - - $html->set_body(' - - - - - - - - - '); - - while (array_keys($roster_con)) { - - $jid = key($roster_con); - $roster_item = array_shift($roster_con); - $nick = $roster_item[nick]; - $grp = $roster_item[group]; - $predefined = $enc->crypt_url("jid=$jid"); - $prepared_jid=str_replace("+", "kezyt2s0", base64_encode($jid)); - if ($col=="e0e9f7") { - - $col="e8eef7"; - - } - else { - - $col="e0e9f7"; - - } - if (in_array($jid,$do_notlog_list) === true) { - - $selected="selected"; - - } - else { - - $selected=""; - - } - if ($selected!="") { - - $col="b7b7b7"; - - } - - $html->set_body(' - - - - - - - '); - - } - - $html->set_body(' - - -
'.$reset_sort[$lang].'
'.$con_tab2[$lang].' ↑↓'.$con_tab3[$lang].' ↑↓'.$con_tab6[$lang].' ↑↓'.$show_chats[$lang].':'.$con_tab4[$lang].'
'.cut_nick(htmlspecialchars($nick)).'('.htmlspecialchars($jid).')'.cut_nick(htmlspecialchars($grp)).''.$show_chat_as_map[$lang].'| - '.$show_chat_stream[$lang].' -
-
- '); - - } - - else { - - $html->status_message('

'.$no_contacts[$lang].'

'); - -} -require_once("footer.php"); - -?> diff --git a/jorge/export.php b/jorge/export.php deleted file mode 100644 index 40b7947..0000000 --- a/jorge/export.php +++ /dev/null @@ -1,208 +0,0 @@ -get('language')) { - - // Validate language setting in session - if (is_language_supported($sess->get('language'),$language_support) === true) { - - require('lang/'.$sess->get('language').'.php'); - - } - else{ - - // In case of invalid session, overwrite value - require('lang/'.$language_support[default_language][0].'.php'); - $sess->set('language',$language_support[default_language][0]); - - } - } - else{ - - // If no lang in sess, set it anyway... - require('lang/'.$language_support[default_language][0].'.php'); - $sess->set('language',$language_support[default_language][0]); - -} - -// language -$lang = $sess->get('language'); - -define(XMPP_HOST,$sess->get('vhost')); -$xmpp_host = str_replace(".","_", XMPP_HOST); - -$rpc_host = check_rpc_server($vhosts[XMPP_HOST],$rpc_port); - -// in case no RPC servers are available stop jorge -if ($rpc_host===false) { - - print "
Currently service is unavailable. Please try again later.
"; - exit; - } - -// connect to xmpp server -$ejabberd_rpc = new rpc_connector("$rpc_host","$rpc_port",XMPP_HOST); - -// initialize encryption system -$enc = new url_crypt(ENC_KEY); - -// authenticate -if (check_registered_user($sess,$ejabberd_rpc,$enc) !== true) { - - header("Location: index.php?act=logout"); - exit; - -} - -// create database object -$db = new db_manager(MYSQL_HOST,MYSQL_NAME,MYSQL_USER,MYSQL_PASS,"mysql","$xmpp_host"); - -// set user data -define(TOKEN,$sess->get('uid_l')); -$db->get_user_id(TOKEN); -define(USER_ID, $db->result->user_id); - -if (!ctype_digit(USER_ID)) { - - // exit on unexpected results - exit; - - } - else{ - - $db->set_user_id(USER_ID); - -} - -// get parameters -$e_string=$_GET['a']; - - -if ($enc->decrypt_url($e_string) === true) { - - $tslice = $enc->tslice; - $talker = $enc->peer_name_id; - $server = $enc->peer_server_id; - - } - else { - - // if validation of link fail, exit - header('Location: index.php'); - exit; - -} - -$db->get_user_name($talker); -$user_name = $db->result->username; -$db->get_server_name($server); -$server_name = $db->result->server_name; -$nickname = $sess->get('export_nickname'); -$db->get_own_name(); -if ($db->result->own_name) { - - $own_name = $db->result->own_name; - - } - else{ - - $own_name = false; - -} - -// get chat -$db->get_user_chat($tslice,$talker,$server,$resource_id = null,$start = null,10000); -$result = $db->result; - -// set headers -header("Cache-Control: public, must-revalidate"); -header("Pragma: hack"); // this is WEIRD - it is needed to work with Internet Explorer :O -header("Content-Type: application/octet-stream"); -header("Content-Disposition: attachment; filename=\"Jorge_chat_$nickname-$tslice.txt\""); - -$data="$export_head1[$lang]$nickname ($user_name@$server_name) $export_head2[$lang] $tslice:\n"; - -foreach ($result as $results) { - - if ($results["direction"] == "from") - { - $out=$nickname; - $tt=$tt+1; - $aa=0; - } - else - { - if ($own_name !== false) { - - $out = $own_name; - } - else{ - - $out = TOKEN; - - } - $aa=$aa+1; - $tt=0; - } - - - if ($aa<2 AND $tt<2) { - - $data .= "\n(".trim(strstr($results[ts], ' ')).") $out\n"; - $here="1"; - } - else - { - $data .=""; $here="0"; - } - - $data .=" $results[body]\n"; - -} - -$data .="\n\n______\nChat exported by Jorge"; - -echo $data; -ob_end_flush(); - -// log event -$db->set_logger("8","1", "JID: $user_name@$server_name, Date: $tslice"); -$sess->unregister('export_nickname'); - -?> diff --git a/jorge/favicon.ico b/jorge/favicon.ico deleted file mode 100644 index 83eccc0..0000000 Binary files a/jorge/favicon.ico and /dev/null differ diff --git a/jorge/favorites.php b/jorge/favorites.php deleted file mode 100644 index c868dce..0000000 --- a/jorge/favorites.php +++ /dev/null @@ -1,178 +0,0 @@ -set_overview('

'.$fav_main[$lang].'

'.$fav_desc[$lang].''); - -// add to favorites -if ($init == "1") { - - if ($enc->decrypt_url($_POST[a]) === true) { - - $tslice = $enc->tslice; - $peer_name_id = $enc->peer_name_id; - $peer_server_id = $enc->peer_server_id; - $db->get_user_name($peer_name_id); - $user_name = $db->result->username; - $db->get_server_name($peer_server_id); - $server_name = $db->result->server_name; - $nick_name = query_nick_name($ejabberd_roster,$user_name, $server_name); - if (!$nick_name) { - - $nick_name = $not_in_r[$lang]; - unset($malpa); - - } - else{ - - $malpa = "@"; - - } - $html->set_body(' -
'.$fav_add[$lang].':
- - - - - -
'.$fav_chat[$lang].''.cut_nick($nick_name).' ('.$user_name.$malpa.$server_name.')
- -
- - - -
-
-
'); - - } - -} - -// process request -if ($_POST[favorite]) { - - if ($enc->decrypt_url($_POST[favorite]) === true) { - - - if ($db->set_favorites($enc->peer_name_id,$enc->peer_server_id,$peer_resource_id,$enc->tslice,$_POST[desc]) === true) { - - $html->status_message($fav_success[$lang]); - - } - else{ - - $html->alert_message($fav_error[$lang]); - - } - - } - -} - -// delete favorites -if ($_GET[del] == "t") { - - if ($db->delete_favorites_id($_GET[link_id]) === true) { - - - $html->status_message($fav_removed[$lang]); - - } - else{ - - $html->alert_message($oper_fail[$lang]); - - } - -} - -// get favorites -$db->get_favorites(); - -if (count($db->result)>0) { - - $html->set_body(' -
- - - - '); - $fav_list = $db->result; - foreach ($fav_list as $row) { - - $db->get_user_name($row[peer_name_id]); - $user_name = $db->result->username; - $db->get_server_name($row[peer_server_id]); - $server_name = $db->result->server_name; - $nickname = query_nick_name($ejabberd_roster,$user_name,$server_name); - $to_base = $enc->crypt_url("tslice=$row[tslice]&peer_name_id=$row[peer_name_id]&peer_server_id=$row[peer_server_id]"); - if (!$row[comment] OR $row[comment] == $my_links_optional[$lang]) { - - $comment = $fav_nocomm[$lang]; - - } - else{ - - $comment = htmlspecialchars($row[comment]); - $comment = str_replace("\n","
",$comment); - $comment = wordwrap($comment,30,"
",true); - - } - if (!$nickname) { - - $nickname = $not_in_r[$lang]; - unset($malpa); - - } - else { - - $malpa = "@"; - - } - $html->set_body(' - - - - - - - '); - - } - $html->set_body('
'.$fav_when[$lang].''.$fav_contact[$lang].''.$fav_comment[$lang].'
'.verbose_date($row[tslice],$months_names,$weekdays).' - '.htmlspecialchars(cut_nick($nickname)).' ('.htmlspecialchars($user_name).$malpa.htmlspecialchars($server_name).') - '.$comment.' '.$fav_remove[$lang].' 
'); - - } - - else { - - $html->status_message('
'.$fav_empty[$lang].'
'); - -} - -require_once("footer.php"); -?> diff --git a/jorge/footer.php b/jorge/footer.php deleted file mode 100644 index ea287c6..0000000 --- a/jorge/footer.php +++ /dev/null @@ -1,126 +0,0 @@ -foot('
'.$quest1[$lang].'
'); - -} - -$html->foot(' -
-
'.$links.'

-
'.$copy.'
-

v1.5-RC1


- '); - -// footer for admins... -$time_end = getmicrotime(); -$time = substr($time_end - $time_start, 0, 10); -if (TOKEN==ADMIN_NAME) { - - $html->foot(''.$admin_site_gen[$lang].$time.'s.'); - -}; - -// execude following code only when user is logged in -if (!preg_match("/index.php/i",$location) AND !preg_match("/not_enabled.php/i",$location)) { - - $html->foot(' - - - - '); - -} - -$html->foot(''); - -// render html output -$html->commit_render(); - -ob_end_flush(); -?> diff --git a/jorge/func.php b/jorge/func.php deleted file mode 100644 index 3455d08..0000000 --- a/jorge/func.php +++ /dev/null @@ -1,932 +0,0 @@ -get_nick("$talker"."@"."$server"); - if ($nickname=="") { - - $nickname=$talker; - - } - - return $nickname; - -} - - -function validate_date($tslice) { - - list($ye, $mo, $da) = split("-", $tslice); - return checkdate($mo,$da,$ye); - -} - - -function check_registered_user ($sess,$ejabberd_rpc,$enc) { - - if (!$sess->is_registered('uid_l') OR !$sess->is_registered('uid_p')) { - - return false; - } - else { - - if ($enc->decrypt_url($sess->get('uid_p')) === true) { - - $uid_p = $enc->single; - - } - else { - - return false; - - } - - $ejabberd_rpc->set_user($sess->get('uid_l'),$uid_p); - if ($ejabberd_rpc->auth() === true) { - - return true; - - } - else { - - return false; - } - - - } - - return false; - -} - - -function is_query_from($query) { - - list($from,$talker,$query_p) = split(":",$query); - $from=trim($from); - if ($from=="from") { - - $qquery[from] = "t"; - $qquery[talker] = trim($talker); - $qquery[talker] = str_replace("//","@",$qquery[talker]); // hack for parametrized search - if ($query_p) { - - $qquery[query] = $query_p; - $qquery[words] = "t"; - return $qquery; - - } - else { - - $qquery[words] = "f"; - return $qquery; - - } - - } - else { - - // normal search - return "f"; - - } - - -} - - -function verbose_date($raw_date,$months_names = null,$weekdays = null,$t = false,$y = false) { - - // English calendar arrays. Here we convert names from english calendar to other language. Make sure your locale in php work with default set to english. - $english_months = array("January","February", "March", "April", "May","June","July","August","September","October", "November","December"); - $english_days = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); - - // Various formats - if ($t === true) { - - return str_replace($english_days,$weekdays,strftime("%e.%m (%A)",strtotime("$raw_date"))); - - } - elseif($y === true) { - - return str_replace($english_months,$months_names,strftime("%B %Y", strtotime("$raw_date"))); - - } - else{ - - return str_replace($english_months,$months_names,strftime("%e %B %Y", strtotime("$raw_date"))); - } - -} - -function validate_start($start) { - - if (!ctype_digit($start)) { - - return false; - - } - if (fmod($start,10)=="0") { - - return true; - - } - else { - - return false; - - } - -} - - -function db_size() { - - $result = mysql_query("show table status"); - $size = 0; - while($row = mysql_fetch_array($result)) { - - $size += $row["Data_length"]; - - } - - $size = round(($size/1024)/1024, 1); - return $size; - -} - - -function verbose_split_line($in_minutes,$verb_h,$in_min) { - - if ($in_minutes>60) { - return $verb_h; - } - elseif ($in_minutes<60) { - return $in_minutes." ".$in_min; - } - -} - - -function cut_nick($nick) { - - if (strlen($nick)> 25) { - $nick=substr($nick,0,25)."..."; - - } - - return $nick; -} - - -function new_parse_url($text) { - - $text = ereg_replace("([[:alpha:]]+://www|[[:alpha:]]+://)[^<>[:space:]]+[[:alnum:]/]", - - "\\0", $text); - - // disabled for now - #$text = ereg_replace("[^://]?www[^<>[:space:]]+[[:alnum:]/]", - # "\\0", $text); - - return $text; -} - - -function calendar($db,$user_id,$xmpp_host,$y,$m,$days,$token,$url_key,$left,$right,$selected,$lang,$view_type,$c_type,$name_peer=0,$server_peer=0,$cal_days=0,$enc=null,$months_names,$weekdays) { - - $days=$days; - $month = $m; - $year = $y; - -//create arrays for the calendar - - $months_days = array("31","28","31","30","31","30","31","31", - "30","31","30","31"); - - $days_array = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun"); - -//removes the 0 from start of month - can't find array key with 0 - - if(strlen($month)==1){ - $month= str_replace("0","",$month); - } - else{ - $month=$month; - } - -//reset month to the array key match (array starts at 0) - - $month= $month-1; - -//find the days in the month - - $days_in_month = $months_days[$month]; - -//$m is used to find month - - $m = $month+1; - -//find the first day of the month - - $time = date("M D Y H:i:s", mktime(0, 0, 0, $m, 1, $year)); - $first_day = explode(" ",$time); - $time = $first_day[1]; - -//create the links to next and previous months - - $next = $month+2; - $x = $year; - -//if month is 13 then new year - - if($next==13){ - $next=1; - $x = $x+1; - } - $prev = $month; - $y = $year; - -//if month is 0, then previous year - - if($prev==0){ - $prev=12; - $y=$y-1; - } - - $calendar = ""; - -//Build the calendar with css -//links to next and previous month only for browser -if ($c_type=="1") { - - // encode links - $link_left = $enc->crypt_url("tslice=$y-$prev"); - $link_right = $enc->crypt_url("tslice=$x-$next"); - - // check if we have chats in prev and next mo - $db->is_left_or_right("$y-$prev"); - $i_left = $db->result; - $db->is_left_or_right("$x-$next"); - $i_right = $db->result; - - - } - else { - - $i_left=0; - $i_right=0; - - } - - $calendar .=' - - - - - - - - - - - - - - - - -
cal_imgcal_img
cal_img - - - - - - - - - - - - - - - - - - '; - - //checks for leap years and add 1 to February - - if(($year % 4 =="") && ($month==1)){ - $days_in_month=$days_in_month+1; - } - - else{ - $days_in_month=$days_in_month; - } - - $new_time=""; - - //find how many blank spaces at beginning of the month - - foreach($days_array as $key=>$value){ - - if($value == $time){ - $new_time .= $key+1; - } - else{ - $new_time .=""; - } - } - - //loop through the days in the month - $c=0; - - for($k=1;$k<($days_in_month+$new_time);$k++){ - - $c++; - if ($c==1) { $calendar.=''; } - - - - //blank space - - if($k<$new_time){ - $calendar.=' - '; - continue; - } - - //start the actual days - - $n = $k-$new_time+1; - - if(in_array($n,$days)){ - - if ($c_type=="1") { - - $to_base = $enc->crypt_url("tslice=$year-$m-$n"); - $loc_orign=""; - - } - elseif($c_type=="2") { - - $to_base = $enc->crypt_url("tslice=$year-$m-$n&peer_name_id=$name_peer&peer_server_id=$server_peer"); - $loc_orign="&loc=2"; - - } - - if ($selected==$n) { $bgcolor = 'bgcolor="#6daae7"'; } else { $bgcolor=""; } - $calendar .= ' - '; - } - else{ - $calendar .= ' - '; - } - - if ($c==7) { $calendar.=''; $c=0; } - - - } - $calendar .= ' - -
- '; - -if ($i_left!=0) { $calendar.='<<<'; } - -$verb_date = "$year-$m-1"; - - $calendar.=' - -  '.verbose_date($verb_date,$months_names,$weekdays,false,true).'  - - '; - if ($i_right!=0) { $calendar.='>>>'; } - $calendar.=' - -
'.$cal_days[$lang][1].''.$cal_days[$lang][2].''.$cal_days[$lang][3].''.$cal_days[$lang][4].''.$cal_days[$lang][5].''.$cal_days[$lang][6].''.$cal_days[$lang][7].'
 '.$n.''.$n.'
-
cal_img
cal_imgcal_img
- - '; - - return($calendar); -} - - -function check_thread($db,$peer_name_id,$peer_server_id,$at,$xmpp_host,$dir=NULL) { - - #adjust this hours as needed, we assume if chat is +/- 1 hour on the edge of day, then chat is related - if ($dir=="1") { - $day="+1 day"; - $bhour="00:00:00"; - $ehour="00:30:00"; - } - elseif($dir=="2"){ - $day="-1 day"; - $bhour="23:30:00"; - $ehour="23:59:59"; - } - - $get_date = date("Y-n-j", strtotime($day, strtotime(date("$at")))); - - $db->check_thread($get_date,$peer_name_id,$peer_server_id,$bhour,$ehour); - if ($db->result > 0) { - - return true; - } - else{ - return false; - - } - - return false; - -} - -function check_rpc_server($rpc_arr,$rpc_port) { - - foreach($rpc_arr as $rpc_host) { - - // assume if response time is greater then 1 second RPC server is down - $fp=fsockopen("$rpc_host", $rpc_port, $errno, $errstr, 1); - if ($fp!=false) { - - return $rpc_host; - - } - - } - - return false; - -} - - -function debug($debug=false,$string) { - - if ($debug===true) { - - print "".htmlspecialchars($string)."
"; - } - - return; - -} - -function message_processor($tslice,$server_name,$start,$nickname,$result_messages,$db,$html,$enc,$token,$split_line,$lang_pack,$lang,$spec_mark,$e_string,$to_base_prev,$to_base_next) { - - /* - This function perform message processing for message archives - tslice - date of chat - server_name - name of server - start - from what point of time of day should chat be displayed - nickname - peer nickname - result_messages - array of messages to be parsed - db - database object - html - html object - enc - encryption object - token - owner name - split_line - config option - lang_pack - array of translations - lang - language pack - spec_mark - marker used to distinguish what we are doing - e_string - url - */ - - // Check if user have set up OwnName - $db->get_own_name(); - if ($db->result->own_name) { - - $own_name = $db->result->own_name; - - } - else{ - - $own_name = false; - - } - - // Main loop - foreach($result_messages as $entry) { - - // always get resource_id if message is type of groupchat - if ($entry[type] !== "groupchat") { - - if ($resource_last !== $entry[peer_resource_id]) { - - if ($db->get_resource_name($entry[peer_resource_id]) === false) { - - return false; - } - - $resource = $db->result->resource_name; - - } - - } - else{ - - if ($db->get_resource_name($entry[peer_resource_id]) === false) { - - return false; - - } - $resource = $db->result->resource_name; - - } - - $resource_last = $entry[peer_resource_id]; - $licz++; - - // marking messages - if ($entry["type"] === "chat" OR $entry["type"] == "") { - - if ($entry["direction"] === "to") { - - $col="main_row_a"; - } - else { - - $col="main_row_b"; - } - } - elseif($entry["type"] === "error") { - - $col="main_row_error"; - - } - elseif($entry["type"] === "normal") { - - $col="main_row_message"; - - } - elseif($entry["type"] === "headline") { - - $col="main_row_headline"; - - } - - $ts = strstr($entry["ts"], ' '); - // time calc - $pass_to_next = $entry["ts"]; - $new_d = $entry["ts"]; - $time_diff = abs((strtotime("$old_d") - strtotime(date("$new_d")))); - $old_d = $pass_to_next; - // end time calc - if ($time_diff>$split_line AND $licz>1) { - - $in_minutes = round(($time_diff/60),0); - $html->set_body(' - '.verbose_split_line($in_minutes,$lang_pack[7],$lang_pack[8]).' -
- '); - } - - // check if chat is continuation from previous day (work only for calendar view) - if ($to_base_prev !== NULL) { - - if ($ts_mark!="1" AND substr($ts, 0 , strpos($ts, ":")) == 00 ) { - - if ( check_thread($db,$talker,$server,$tslice,$xmpp_host,2) === true) { - - $html->set_body(''.$lang_pack[0].''); - } - // check only first line - $ts_mark="1"; - } - - } - - // run code only if type is not groupchat - if ($entry["type"] !== "groupchat") { - - // setting subject - if ($col==="main_row_message" OR $col==="main_row_headline") { - - if ($entry["subject"]) { - - $subject = ": ".$entry["subject"]; - - } - else{ - - unset($subject); - - } - - } - - // add line in case of special message - if ($col==="main_row_message") { - - $html->set_body(''.$lang_pack[1].' '.htmlspecialchars($subject).''); - - } - - if ($col==="main_row_error") { - - $html->set_body(''.$lang_pack[2].''); - - } - - if ($col==="main_row_headline") { - - $html->set_body(''.$lang_pack[3].' '.htmlspecialchars($subject).''); - - } - - } - - // calculate chat direction, whether to display nick... - if ($entry["direction"] == "from") { - - $out=$nickname; - $tt=$tt+1; - $aa=0; - - } - else{ - - $out = $token; - $aa=$aa+1; - $tt=0; - - } - - // timestamp, beginning of the chatline - if ($entry["type"] !== "groupchat") { - - $html->set_body(''.$ts.''); - - } - else{ - - if ($out!==$token) { - - // colorize - if ($resource_group === $resource OR !$resource_group) { - - if (!$col) { - - $col = "main_row_group_to"; - - } - $col=$col; - - } - else{ - - if($col === "main_row_group_from") { - - $col="main_row_group_to"; - } - else{ - - $col="main_row_group_from"; - - } - - } - $html->set_body(''.$ts.''); - - } - } - - // different bahaviour for groupchat and other messages - if ($entry["type"] !== "groupchat") { - - if ($aa<2 AND $tt<2) { - - $html->set_body(''); - if ($out === TOKEN) { - - // display of Own Name - if ($own_name !== false) { - - $html->set_body(cut_nick(htmlspecialchars($own_name))); - - } - else{ - - $html->set_body(cut_nick(htmlspecialchars($out))); - - } - - } - else{ - - $html->set_body(cut_nick(htmlspecialchars($out))); - - } - - $html->set_body(''); - - if ($out !== $token) { - - if ($spec_mark === false) { - - $html->set_body(' -
- - '.cut_nick(htmlspecialchars($resource)).'
- '); - - } - else{ - - $html->set_body('
- '.cut_nick(htmlspecialchars($server_name)).'
- '); - } - - } - - $html->set_body(''); - $here = "1"; - - } - else { - - $html->set_body('-'); - $here = "0"; - - } - - } - else{ - - // do not display own chats sent to MUC. Here resource is actualy nickname as MUC standard specify - if ($out !== $token) { - - if ($resource_group !== $resource) { - - // if message is sent without resource, that must be channel message, advise user. - if ($resource === "") { - - $resource = $lang_pack[5]; - - } - - $html->set_body('MUC: '.cut_nick($out).' -
'.cut_nick(htmlspecialchars($resource)).'
- '); - $here = "1"; - $resource_group = $resource; - - } - else{ - - $html->set_body('-'); - $here = "0"; - - } - - } - else{ - - $here = "0"; - - } - } - - // process body part, do not show chat if message is type of groupchat - // this is sadly funny i write this 'if' and i dont know what exacly it do :/ - - if ($out !== $token OR $entry["type"] !== "groupchat") { - - // prepare body - $new_s = htmlspecialchars($entry["body"]); - $to_r = array("\n"); - $t_ro = array("
"); - $new_s = str_replace($to_r,$t_ro,$new_s); - $new_s = wordwrap($new_s,107,"
",true); - $new_s = new_parse_url($new_s); - $html->set_body(''.$new_s.''); - // generate mylink only on selected lines - if ($here==="1") { - - $lnk = $enc->crypt_url("tslice=$tslice&peer_name_id=$entry[peer_name_id]&peer_server_id=$entry[peer_server_id]"); - $to_base2 = $enc->crypt_url("tslice=$tslice&peer_name_id=$entry[peer_name_id]&peer_server_id=$entry[peer_server_id]&ismylink=1&linktag=$licz&lnk=$lnk&strt=$start"); - $html->set_body(''.$lang_pack[6].''); - - } - else { - - $html->set_body(''); - - } - - if ($t=2) { $c=1; $t=0; } // WTF!? - - $html->set_body(''); - - } - - } - - - $html->set_body(''); - - // Check thread. Work only for calendar view. - if ($to_base_next !== NULL) { - - if (substr($ts, 0 , strpos($ts, ":")) == 23 AND date("Y-n-j") !== $tslice) { - - if ( check_thread($db,$talker,$server,$tslice,$xmpp_host,1) === true) { - - $html->set_body(''.$lang_pack[9].''); - - } - } - - } - - return true; - -} - -function is_language_supported($l_query,$language_support,$l_key = 0, $return_val = false) { - - while (array_keys($language_support)) { - - $lang_key = key($language_support); - if ($l_query === $language_support[$lang_key][$l_key]) { - - if ($return_val === true) { - - return $language_support[$lang_key][0]; - - } - else { - - return true; - - } - - } - - array_shift($language_support); - - } - - return false; - -} - - -?> diff --git a/jorge/headers.php b/jorge/headers.php deleted file mode 100644 index 55cf285..0000000 --- a/jorge/headers.php +++ /dev/null @@ -1,371 +0,0 @@ -set('language',$c_language); - debug(DEBUG,"Language found, loading file: $c_language.php"); - require("lang/".$c_language.".php"); - $language_found = true; - - } - else{ - - setcookie("jorge_language",$language_support[default_language][0],time()+2592000); - $sess->set('language',$language_support[default_language][0]); - debug(DEBUG,"Language not found in selection, using defaults"); - require('lang/'.$language_support[default_language][0].'.php'); - } - -} - -// get client addr -$rem_adre = $_SERVER['REMOTE_ADDR']; - -// something for mac users -$mac_user = get_user_agent($_SERVER); - -// location -$location=$_SERVER['PHP_SELF']; - -// init html helper -$html = new render_html(); - -if (!preg_match("/index.php/i",$location)) { - - if ($sess->get('vhost') === null) { - - header("Location: index.php?act=logout"); - - } - if (array_key_exists($sess->get('vhost'), $vhosts) === false) { - - header("Location: index.php?act=logout"); - - } - - define(XMPP_HOST,$sess->get('vhost')); - $rpc_host = check_rpc_server($vhosts[XMPP_HOST],$rpc_port); - debug(DEBUG,"Active RPC host: $rpc_host"); - - // in case no RPC servers are available stop jorge - if ($rpc_host===false) { - - print "
Currently service is unavailable. Please try again later.
- Please logout -
"; - exit; - } - - // create rpc object - $ejabberd_rpc = new rpc_connector("$rpc_host","$rpc_port",XMPP_HOST); - $xmpp_host = str_replace(".","_", XMPP_HOST); - - } - else{ - - // check if selected host exist in configuration - if (array_key_exists($_POST['vhost'], $vhosts) === true) { - - $rpc_host = check_rpc_server($vhosts[$_POST['vhost']],$rpc_port); - debug(DEBUG,"Selecting RPC server during login: $rpc_host"); - if ($rpc_host === false) { - - print "
Currently service is unavailable. Please try again later.
- Please logout -
"; - exit; - - } - else { - - define(XMPP_HOST,$_POST['vhost']); - $ejabberd_rpc = new rpc_connector("$rpc_host","$rpc_port",XMPP_HOST); - $xmpp_host = str_replace(".","_", XMPP_HOST); - - } - - } - else{ - - unset($_POST['inpLogin']); - unset($_POST['inpPass']); - - // Try to recreate db object... - if ($_GET['act'] === "logout") { - - if ($sess->get('vhost')!="") { - - $xmpp_host = str_replace(".","_", $sess->get('vhost')); - - } - } - - } - -} - -// create db_manager object -$db = new db_manager(MYSQL_HOST,MYSQL_NAME,MYSQL_USER,MYSQL_PASS,"mysql","$xmpp_host"); -$db->set_debug(SQL_DEBUG); - -// create encryption object -$enc = new url_crypt(ENC_KEY); - -// username (token) -define(TOKEN,$sess->get('uid_l')); - -//debug -debug(DEBUG,"User session:".TOKEN); - -// authentication checks. Ensure if session data is not altered... (only when we are inside Jorge) -if (!preg_match("/index.php/i",$location)) { - - if (check_registered_user($sess,$ejabberd_rpc,$enc) !== true) { - - header("Location: index.php?act=logout"); - exit; - } - - // Load language file based on current session - debug(DEBUG,"Selecting initial language after authentication"); - if ($sess->get('language')) { - - // Validate language setting in session - if (is_language_supported($sess->get('language'),$language_support) === true) { - - debug(DEBUG,"Language selection ok."); - require('lang/'.$sess->get('language').'.php'); - - } - else{ - - debug(DEBUG,"Language in session was altered! Overwritting value..."); - require('lang/'.$language_support[default_language][0].'.php'); - $sess->set('language',$language_support[default_language][0]); - - } - } - - // we need user_id but only if we are not in not_enabled mode: - if(!preg_match("/not_enabled.php/i",$_SERVER['PHP_SELF'])) { - - $db->get_user_id(TOKEN); - $user_id = $db->result->user_id; - // create user_id instance - $db->set_user_id($user_id); - } - -} - -// check if user have admin rights -if (in_array(TOKEN, $vhosts_admins[XMPP_HOST]) === true) { - - define(ADMIN_NAME,TOKEN); - -} - -// run only for admins -if (TOKEN === ADMIN_NAME) { - - $time_start=getmicrotime(); - -} - -// If language not set or not found in cookie, set default language -if (preg_match("/index.php/i",$location) OR preg_match("/not_enabled.php/i",$location)) { - - // Set defaults only if language was not selected - if ($language_found !== true) { - - if (is_language_supported($_COOKIE["jorge_language"],$language_support) === true) { - - debug(DEBUG,"Setting language according to cookie"); - require('lang/'.$_COOKIE["jorge_language"].'.php'); - $sess->set('language',$_COOKIE["jorge_language"]); - - } - else { - - debug(DEBUG,"Language cookie not found, using defaults"); - require('lang/'.$language_support[default_language][0].'.php'); - $sess->set('language',$language_support[default_language][0]); - - } - - - } - -} - -// Get language from session -$lang=$sess->get('language'); - -$html->headers(' - - - - - - - - - - - - - - - '); - -if (preg_match("/main.php/i",$location)) { - - $html->headers(' - - - '); -} -$html->headers(' - - - - - - - '); - -// prevent loading includes as long as user is not admin. -if (TOKEN==ADMIN_NAME) { - - $html->headers(''); -} -$html->headers(' - Jorge Beta - - - - - - - - - '); - -?> - diff --git a/jorge/help.php b/jorge/help.php deleted file mode 100644 index 4bea4e4..0000000 --- a/jorge/help.php +++ /dev/null @@ -1,29 +0,0 @@ -set_body('

'.$help_but[$lang].'

'.$help_notice[$lang].''.$help_search_tips[$lang].$help_my_links_note[$lang].$help_advanced_tips[$lang]); - -require_once("footer.php"); -?> diff --git a/jorge/img/apple-logo.png b/jorge/img/apple-logo.png deleted file mode 100644 index 1959bad..0000000 Binary files a/jorge/img/apple-logo.png and /dev/null differ diff --git a/jorge/img/bak2a.png b/jorge/img/bak2a.png deleted file mode 100644 index 4e853f6..0000000 Binary files a/jorge/img/bak2a.png and /dev/null differ diff --git a/jorge/img/bak2b.png b/jorge/img/bak2b.png deleted file mode 100644 index d488739..0000000 Binary files a/jorge/img/bak2b.png and /dev/null differ diff --git a/jorge/img/bar_bg.png b/jorge/img/bar_bg.png deleted file mode 100644 index 0114242..0000000 Binary files a/jorge/img/bar_bg.png and /dev/null differ diff --git a/jorge/img/bar_new.png b/jorge/img/bar_new.png deleted file mode 100644 index 5977762..0000000 Binary files a/jorge/img/bar_new.png and /dev/null differ diff --git a/jorge/img/bell-bak.png b/jorge/img/bell-bak.png deleted file mode 100644 index d0a8175..0000000 Binary files a/jorge/img/bell-bak.png and /dev/null differ diff --git a/jorge/img/bell-down.png b/jorge/img/bell-down.png deleted file mode 100644 index fe760d5..0000000 Binary files a/jorge/img/bell-down.png and /dev/null differ diff --git a/jorge/img/cal_bck.png b/jorge/img/cal_bck.png deleted file mode 100644 index 1246336..0000000 Binary files a/jorge/img/cal_bck.png and /dev/null differ diff --git a/jorge/img/cal_bck2.png b/jorge/img/cal_bck2.png deleted file mode 100644 index c33521f..0000000 Binary files a/jorge/img/cal_bck2.png and /dev/null differ diff --git a/jorge/img/cal_bck_bot.png b/jorge/img/cal_bck_bot.png deleted file mode 100644 index 8b3818d..0000000 Binary files a/jorge/img/cal_bck_bot.png and /dev/null differ diff --git a/jorge/img/cal_bck_left.png b/jorge/img/cal_bck_left.png deleted file mode 100644 index 304307c..0000000 Binary files a/jorge/img/cal_bck_left.png and /dev/null differ diff --git a/jorge/img/cal_bck_left2.png b/jorge/img/cal_bck_left2.png deleted file mode 100644 index dee5d31..0000000 Binary files a/jorge/img/cal_bck_left2.png and /dev/null differ diff --git a/jorge/img/cal_bck_right.png b/jorge/img/cal_bck_right.png deleted file mode 100644 index aa6b695..0000000 Binary files a/jorge/img/cal_bck_right.png and /dev/null differ diff --git a/jorge/img/cal_bck_right2.png b/jorge/img/cal_bck_right2.png deleted file mode 100644 index 464b447..0000000 Binary files a/jorge/img/cal_bck_right2.png and /dev/null differ diff --git a/jorge/img/cal_bck_top.gif b/jorge/img/cal_bck_top.gif deleted file mode 100644 index 10bd5bf..0000000 Binary files a/jorge/img/cal_bck_top.gif and /dev/null differ diff --git a/jorge/img/cal_corn_11.png b/jorge/img/cal_corn_11.png deleted file mode 100644 index e3328ad..0000000 Binary files a/jorge/img/cal_corn_11.png and /dev/null differ diff --git a/jorge/img/cal_corn_12.png b/jorge/img/cal_corn_12.png deleted file mode 100644 index 9892714..0000000 Binary files a/jorge/img/cal_corn_12.png and /dev/null differ diff --git a/jorge/img/cal_corn_21.png b/jorge/img/cal_corn_21.png deleted file mode 100644 index f0a4c48..0000000 Binary files a/jorge/img/cal_corn_21.png and /dev/null differ diff --git a/jorge/img/cal_corn_22.png b/jorge/img/cal_corn_22.png deleted file mode 100644 index b44ed85..0000000 Binary files a/jorge/img/cal_corn_22.png and /dev/null differ diff --git a/jorge/img/closed.png b/jorge/img/closed.png deleted file mode 100644 index 26f03a4..0000000 Binary files a/jorge/img/closed.png and /dev/null differ diff --git a/jorge/img/indicator.gif b/jorge/img/indicator.gif deleted file mode 100644 index 085ccae..0000000 Binary files a/jorge/img/indicator.gif and /dev/null differ diff --git a/jorge/img/jorge_logo.png b/jorge/img/jorge_logo.png deleted file mode 100644 index 14316e2..0000000 Binary files a/jorge/img/jorge_logo.png and /dev/null differ diff --git a/jorge/img/list.png b/jorge/img/list.png deleted file mode 100644 index fe5682a..0000000 Binary files a/jorge/img/list.png and /dev/null differ diff --git a/jorge/img/loader.gif b/jorge/img/loader.gif deleted file mode 100644 index b885421..0000000 Binary files a/jorge/img/loader.gif and /dev/null differ diff --git a/jorge/img/logo_jabster2.png b/jorge/img/logo_jabster2.png deleted file mode 100644 index 4d8042f..0000000 Binary files a/jorge/img/logo_jabster2.png and /dev/null differ diff --git a/jorge/img/open.png b/jorge/img/open.png deleted file mode 100644 index 1b51b7b..0000000 Binary files a/jorge/img/open.png and /dev/null differ diff --git a/jorge/img/shadow.png b/jorge/img/shadow.png deleted file mode 100644 index 904dda9..0000000 Binary files a/jorge/img/shadow.png and /dev/null differ diff --git a/jorge/img/spinner.gif b/jorge/img/spinner.gif deleted file mode 100644 index f4347b8..0000000 Binary files a/jorge/img/spinner.gif and /dev/null differ diff --git a/jorge/index.php b/jorge/index.php deleted file mode 100644 index c5f135e..0000000 --- a/jorge/index.php +++ /dev/null @@ -1,384 +0,0 @@ -get('uid_l')) { - - if ($sess->get('view_type') == "1") { - - header ("Location: main.php"); - - } - else { - - header ("Location: calendar_view.php"); - - } - -} - -// get post data -$inpLogin = strtolower($_POST['inpLogin']); -$inpPass = $_POST['inpPass']; - -if ($wo_sess || $inpLogin || $inpPass) { - - // set attepts in cookies - if ($_COOKIE["auth_attempt"]=="") { - - // show captcha anyway if user comes for the first time or have disabled cookies - setcookie("auth_attempt",1,time()+600); - $auth_attempt = "3"; - - } - else{ - - $auth_attempt = $_COOKIE["auth_attempt"] + 1; - settype($auth_attempt,"string"); - // if it is not numeric let set it to some high value - if (!ctype_digit($auth_attempt)) { - - $auth_attempt = "100"; - - } - - setcookie("auth_attempt",$auth_attempt,time()+600); - } - - // on 3rd attempt - check captcha - if ($auth_attempt >= "3") { - - $resp = recaptcha_check_answer(CAPTCHA_PRIVATE, - $_SERVER["REMOTE_ADDR"], - $_POST["recaptcha_challenge_field"], - $_POST["recaptcha_response_field"]); - - - if (!$resp->is_valid) { - - unset($inpPass); - unset($inpLogin); - $html->system_message($wrong_data2[$lang]); - - } - - } - -} - -if ($_GET['act']==="logout") { - - if ($db->get_user_id(TOKEN) === true) { - - if($db->result->user_id) { - - $db->set_user_id($db->result->user_id); - $db->set_logger("2","1",$rem_adre); - - } - - } - - $sess->finish(); - header("Location: index.php"); - exit; - - } - - else { - - if ($inpLogin!="" || $inpPass!="") { - - $ejabberd_rpc->set_user($inpLogin,$inpPass); - if ($ejabberd_rpc->auth() === true) { - - $sess->set('login',$inpLogin); - $sess->set('uid_l',$inpLogin); - $sess->set('uid_p',$enc->crypt_url("single=$inpPass")); - $sess->set('vhost',XMPP_HOST); - // remember user choice - setcookie("fav_host", XMPP_HOST,time()+2592000); - setcookie("auth_attempt",0,time()+2592000); - // Get user_id if it is possible - if ($db->get_user_id($sess->get('uid_l')) === true) { - - $ui = $db->result->user_id; - $db->set_user_id($ui); - $db->is_log_enabled(); - $ret_v = $db->result->is_enabled; - - } - else { - - $ret_val = null; - } - - if ($ret_v === true OR $ret_v === false) { - - $sess->set('log_status',$ret_v); - $db->set_logger("1","1",$rem_adre); - // get preferences, if not set, fallback to standard view. - $db->get_jorge_pref(); - $pref_res = $db->result; - foreach ($pref_res as $res_pref) { - - if ($res_pref[pref_id]=="1") { - - if ($res_pref[pref_value] == "2") { - - $view_type = "2"; - $tmp_v = "calendar_view.php"; - - } - elseif($res_pref[pref_value] == "1") { - - $view_type = "1"; - $tmp_v = "main.php"; - - } - - $sess->set('view_type',$view_type); - } - - if ($res_pref[pref_id] == "2") { - - // Check if language is supported, return value if it is - $check_language = is_language_supported($res_pref[pref_value],$language_support,1,true); - - // function can return true/false/value, in this case we need value and not false - if ($check_language !== false) { - - // set language according to database setup - setcookie("jorge_language",$check_language,time()+2592000); - $sess->set('language',$check_language); - - } - else{ - - // this is where language was not found in settings, so use default - setcookie("jorge_language",$language_support[default_language][1],time()+2592000); - $sess->set('language',$check_language); - - } - - } - } - - if ($tmp_v=="") { - - $sess->set('view_type',2); - $tmp_v="calendar_view.php"; - } - - header("Location: $tmp_v"); - exit; // lets break script at this point... - - } - - else { - - $sess->set('log_status',null); - header("Location: not_enabled.php"); - exit; - } - - } - - if (no_vhost === true) { - - $html->system_message($vhost_not_selected[$lang]); - - } - else{ - - $html->system_message($wrong_data[$lang]); - - } - $db->get_user_id($inpLogin); - $ui_fail = $db->result->user_id; - - // Workaround, if user_id is not know, do not alter login attempts - if ($ui_fail) { - - $db->get_last_attempt($ui_fail); - $row = $db->result->cnt; - - } - else{ - - $row="0"; - - } - - // bump log_level if more then 3 log attempts in one minute - if ($row > "3") { - - $log_level = "3"; - - } - else { - - $log_level = "2"; - - } - - if ($ejabberd_rpc->check_account() === true) { - - $db->set_user_id($ui_fail); - $db->set_logger("3",$log_level,$rem_adre); - - } - - } - -} - - -$html->set_body(' - - - - '); - -$html->set_body(' -

Branding logo
- - - - - - - -
'.$welcome_1[$lang].'
-
- -
-
-
-
-

- - - - - - '); - - // display captcha on 3rd attempt... - $check_cookie = $_COOKIE["auth_attempt"]; - settype($check_cookie,"string"); - if (!ctype_digit($check_cookie) OR $check_cookie=="") { - - $cookie_failed = true; - - } - else{ - - $cookie_failed = false; - - } - - if ($check_cookie >= "2" OR $cookie_failed === true) { - - $html->set_body(' - '); - - } - - $html->set_body(' -
'.$login_w[$lang].'  - - '); - -// vhost support -$vhost_count = count($vhosts); -if ($vhost_count>1) { - - $html->set_body(''); - - - } - else{ - - // There is only one vhost configured, so do not display select box - $html->set_body('@'.key($vhosts).''); - -} - -$html->set_body('
'.$passwd_w[$lang].' 
'.recaptcha_get_html(CAPTCHA_PUBLIC,$error = null, $use_ssl = true).'
- '); - -require_once("footer.php"); -?> diff --git a/jorge/install/jorge.sql b/jorge/install/jorge.sql deleted file mode 100644 index a0a1fd0..0000000 --- a/jorge/install/jorge.sql +++ /dev/null @@ -1,182 +0,0 @@ --- MySQL schema for project Jorge - --- --- Table structure for table `jorge_favorites` --- - -DROP TABLE IF EXISTS `jorge_favorites`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_favorites` ( - `owner_id` int(11) default NULL, - `peer_name_id` int(11) default NULL, - `peer_server_id` int(11) default NULL, - `resource_id` int(11) default NULL, - `tslice` varchar(20) default NULL, - `comment` varchar(50) default NULL, - `ext` int(11) default NULL, - `link_id` int(10) unsigned NOT NULL auto_increment, - `vhost` varchar(255) default NULL, - PRIMARY KEY (`link_id`), - KEY `jorge_favorites_ext_idx` (`owner_id`,`ext`), - KEY `favorites_idx` (`owner_id`,`peer_name_id`,`peer_server_id`,`tslice`,`vhost`) -) ENGINE=InnoDB AUTO_INCREMENT=100 DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `jorge_logger` --- - -DROP TABLE IF EXISTS `jorge_logger`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_logger` ( - `id_user` int(11) default NULL, - `id_log_detail` int(11) default NULL, - `id_log_level` int(11) default NULL, - `log_time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, - `extra` text, - `vhost` varchar(255) default NULL, - KEY `logger_idx` (`id_user`,`id_log_detail`,`id_log_level`,`vhost`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `jorge_logger_level_dict` --- - -DROP TABLE IF EXISTS `jorge_logger_level_dict`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_logger_level_dict` ( - `id_level` smallint(6) NOT NULL, - `level` varchar(20) default NULL, - `lang` varchar(3) NOT NULL default '', - PRIMARY KEY (`id_level`,`lang`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `jorge_logger_dict` --- - -DROP TABLE IF EXISTS `jorge_logger_dict`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_logger_dict` ( - `id_event` smallint(6) NOT NULL, - `event` text, - `lang` varchar(3) NOT NULL default 'eng', - PRIMARY KEY (`id_event`,`lang`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `jorge_mylinks` --- - -DROP TABLE IF EXISTS `jorge_mylinks`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_mylinks` ( - `id_link` int(11) NOT NULL auto_increment, - `owner_id` int(11) default NULL, - `peer_name_id` int(11) default NULL, - `peer_server_id` int(11) default NULL, - `datat` text, - `link` text, - `description` text, - `ext` int(11) default NULL, - `link_id` int(11) default NULL, - `vhost` varchar(255) default NULL, - PRIMARY KEY (`id_link`), - KEY `mylinks_idx` (`owner_id`,`vhost`) -) ENGINE=InnoDB AUTO_INCREMENT=454 DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `jorge_pref` --- - -DROP TABLE IF EXISTS `jorge_pref`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_pref` ( - `owner_id` int(11) default NULL, - `pref_id` int(11) default NULL, - `pref_value` int(11) default NULL, - `vhost` varchar(255) default NULL, - KEY `pref_idx` (`owner_id`,`vhost`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `jorge_stats` --- - -DROP TABLE IF EXISTS `jorge_stats`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_stats` ( - `day` date default NULL, - `hour` tinyint(4) default NULL, - `value` int(11) default NULL, - `vhost` varchar(255) default NULL, - KEY `stats_idx` (`day`,`vhost`), - PRIMARY KEY (`day`,`hour`,`vhost`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `pending_del` --- - -DROP TABLE IF EXISTS `pending_del`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `pending_del` ( - `owner_id` int(11) default NULL, - `peer_name_id` int(11) default NULL, - `date` varchar(20) default NULL, - `peer_server_id` int(11) default NULL, - `timeframe` timestamp NOT NULL default CURRENT_TIMESTAMP, - `type` enum('chat','favorite','mylink','other') default NULL, - `idx` smallint(6) default NULL, - `vhost` varchar(255) default NULL, - KEY `pending_idx` (`owner_id`,`peer_name_id`,`peer_server_id`,`date`,`type`,`idx`,`vhost`), - KEY `pending_time_idx` (`timeframe`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `jorge_self_names` --- - -DROP TABLE IF EXISTS `jorge_self_names`; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -CREATE TABLE `jorge_self_names` ( - `owner_id` int(11) NOT NULL, - `own_name` varchar(60) NOT NULL, - `vhost` varchar(255) NOT NULL, - PRIMARY KEY (`owner_id`,`vhost`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -SET character_set_client = @saved_cs_client; - --- --- Inserting logger dictionary --- - -LOCK TABLES `jorge_logger_dict` WRITE; -/*!40000 ALTER TABLE `jorge_logger_dict` DISABLE KEYS */; -INSERT INTO `jorge_logger_dict` VALUES (1,'Logged in','eng'),(2,'Logged out','eng'),(3,'Login failed','eng'),(4,'Deleted chat thread','eng'),(5,'Deleted whole archive','eng'),(6,'Turned off archivization','eng'),(7,'Turned on archivization','eng'),(8,'Chat exported','eng'),(9,'Deleted entire archive','eng'); -/*!40000 ALTER TABLE `jorge_logger_dict` ENABLE KEYS */; -UNLOCK TABLES; - -LOCK TABLES `jorge_logger_level_dict` WRITE; -/*!40000 ALTER TABLE `jorge_logger_level_dict` DISABLE KEYS */; -INSERT INTO `jorge_logger_level_dict` VALUES (1,'normal','eng'),(2,'warn','eng'),(3,'alert','eng'); -/*!40000 ALTER TABLE `jorge_logger_level_dict` ENABLE KEYS */; -UNLOCK TABLES; - --- EOF diff --git a/jorge/jquery.autocomplete.css b/jorge/jquery.autocomplete.css deleted file mode 100644 index 402ab12..0000000 --- a/jorge/jquery.autocomplete.css +++ /dev/null @@ -1,48 +0,0 @@ -.ac_results { - padding: 0px; - border: 1px solid black; - background-color: white; - overflow: hidden; - z-index: 99999; -} - -.ac_results ul { - width: 100%; - list-style-position: outside; - list-style: none; - padding: 0; - margin: 0; -} - -.ac_results li { - margin: 0px; - padding: 2px 5px; - cursor: default; - display: block; - /* - if width will be 100% horizontal scrollbar will apear - when scroll mode will be used - */ - /*width: 100%;*/ - font: menu; - font-size: 12px; - /* - it is very important, if line-height not setted or setted - in relative units scroll will be broken in firefox - */ - line-height: 16px; - overflow: hidden; -} - -.ac_loading { - background: white url('img/indicator.gif') right center no-repeat; -} - -.ac_odd { - background-color: #eee; -} - -.ac_over { - background-color: #0A246A; - color: white; -} diff --git a/jorge/lang/core.php b/jorge/lang/core.php deleted file mode 100644 index df6b799..0000000 --- a/jorge/lang/core.php +++ /dev/null @@ -1,44 +0,0 @@ - diff --git a/jorge/lang/eng.php b/jorge/lang/eng.php deleted file mode 100644 index 746a1f5..0000000 --- a/jorge/lang/eng.php +++ /dev/null @@ -1,329 +0,0 @@ - - WARNING - We are still testing the system, that mean it may not work at all or work wrong or even lead to datalost. Use it at your own risk!"; -$welcome_1[eng] = "Welcome to Jorge - message archives. Please login"; -$login_w[eng] = "Login"; -$passwd_w[eng] = "Password"; -$login_act[eng] = "Sign in"; -$devel_info[eng] = "Development version"; -$activate_m[eng] = "Enable message archiving"; -$ch_lan[eng] = "Change language to:"; -$ch_lan2[eng] = "Zmień język na "; -$lang_sw[eng] = "Polski"; -$lang_sw2[eng] = "Angielski"; -$header_l[eng] = "Message archives of server"; -$menu_item_browser[eng] = "Browser"; -$menu_item_map[eng] = "Chat Map"; -$menu_item_fav[eng] = "Favorites"; -$menu_item_search[eng] = "Search"; -$menu_item_links[eng] = "MyLinks"; -$menu_item_panel[eng] = "Control Panel"; -$menu_item_contacts[eng] = "Contacts"; -$menu_item_logs[eng] = "Logs"; -$menu_item_trash[eng] = "Trash"; -$filter_form[eng] = "Filter your contacts *"; -$filter_form_tip[eng] = "Type contact name"; -$filter_tip[eng] = "...and next select it from list, or search contact list by hand:"; -$ff_notice[eng] = "This function work only in Firefox browser"; -$search_box[eng] = "Search in archives"; -$search_tip[eng] = "Displaying"; -$search_why[eng] = " search results (not more then 100). Find out why"; -$search_warn[eng] = "Warning: Showing results only from selected time range"; -$all_for_u[eng] = "Show conversations with this user using: "; -$all_for_u_m[eng] = "stream"; -$all_for_u_m_d[eng] = "Show all conversations with this user as stream"; -$all_for_u_m2[eng] = "map"; -$all_for_u_m2_d[eng] = "Show all conversations with this user as chat map"; -$all_for_u_t[eng] = "Show all chats from this user"; -$arch_on[eng] = "Turn on archivization"; -$arch_off[eng] = "Turn off archivization"; -$log_out_b[eng] = "Sign out"; -$archives_t[eng] = "Archive browser"; -$main_date[eng] = "Date:"; -$talks[eng] = "Conversation list:"; -$thread[eng] = "Content:"; -$time_t[eng] = "Time:"; -$user_t[eng] = "User:"; -$my_links_save[eng] = "MyLinks"; -$my_links_desc_m[eng] = "MyLinks - Your links"; -$my_links_desc_e[eng] = "Here you can find saved fragments of your chats"; -$settings_desc[eng] = "Archive settings"; -$settings_desc_detail[eng] = "The panel consist of options that let you control message archiving as well as options regarding your account"; -$api_access_enable[eng] = "Enable API access for this account"; -$api_access_disable[eng] = "Disable API access for this account"; -$api_access_off[eng] = "API access is enabled for this account"; -$api_access_learn[eng] = "Learn more about public API"; -$print_t[eng] = "print"; -$del_t[eng] = "delete"; -$resource_only[eng] = "Show chat only with this resource"; -$resource_warn[eng] = "Showing chat only with resource: "; -$resource_discard[eng] = "Show "; -$resource_discard2[eng] = "entire chat thread."; -$del_all_conf[eng] = "You are about to delete all your message archives. Are you *really* sure?\\nWARNING: It would be impossible to recover your archives!"; -$deleted_all[eng] = "All your message archive has been deleted"; -$delete_nothing[eng] = "Your message archive is empty. Nothing was deleted"; -$delete_error[eng] = "Ooops...There were errors during processing your request. Please try again later"; -$search_w1[eng] = "Search string cannot be shorter than 3 and longer than 70 characters..."; -$search_res[eng] = "Search results: "; -$my_links_save_d[eng] = "Saving link. Fill the form below"; -$my_links_optional[eng] = "Description (optional, max 120 characters)"; -$my_links_chat[eng] = "Conversation with:"; -$my_links_commit[eng] = "save"; -$my_links_cancel[eng] = "cancel"; -$my_links_link[eng] = "Link from day:"; -$my_links_desc[eng] = "Description:"; -$my_links_added[eng] = "Link succesfuly added!"; -$my_links_back[eng] = "Back to chat"; -$my_links_removed[eng] = "Link succesfuly deleted"; -$my_links_none[eng] = "No decsription"; -$status_msg1[eng] = "Message archiving is disabled by user"; -$status_msg2[eng] = "Message archiving have beed enabled. Changes may take 10s"; -$status_msg3[eng] = "Message archiving have beed disabled. Changes may take 10s"; -$my_links_no_links[eng] = "You don't have any MyLinks saved..."; -$quest1[eng] = "Found error? Fill bug report!"; -$search1[eng] = "Search..."; -$no_result[eng] = "No search results"; -$settings_del[eng] = "Delete entire archive"; -$del_conf[eng] = "Do you really want to delete this chat?"; -$del_conf_my_link[eng] = "Do you really want to remove that link?"; -$not_in_r[eng] = "Special contact"; -$del_moved[eng] = "Conversation moved to trash."; -$del_info[eng] = "Conversation have been deleted"; -$undo_info[eng] = "Conversation restored succesfuly"; -$del_my_link[eng] = "delete"; -$help_but[eng] = "Help"; -$tip_delete[eng] = "Delete this conversation"; -$tip_export[eng] = "Export this conversation to text file"; -$customize1[eng] = "Customize logging"; -$from_u[eng] = "From: "; -$to_u[eng] = "To: "; -$search_next[eng] = "Next results..."; -$search_prev[eng] = "Previous results..."; -$change_pass[eng] = "Change password"; -$no_contacts[eng] = "Your contacts list is currently empty"; -$no_archives[eng] = "Currently you dont have any chats saved"; -$con_tab1[eng] = "No."; -$con_tab2[eng] = "Contact name"; -$con_tab3[eng] = "JabberID"; -$con_tab4[eng] = "Enable archiving"; -$con_tab_act_y[eng] = "Yes"; -$con_tab_act_n[eng] = "No"; -$con_tab_submit[eng] = "Save changes"; -$con_tab6[eng] = "Group"; -$con_no_g[eng] = "No group"; -$map_no_g[eng] = "no group"; -$con_head[eng] = "Contacts managment"; -$con_notice[eng] = "Notice: displaying only contacts with assigned nicknames."; -$con_title[eng] = "Click on contact name to see conversation history"; -$con_saved[eng] = "Changes have beed saved"; -$help_notice[eng] = "Main topics"; -$nx_dy[eng] = "Next day"; -$no_more[eng] = "No more search results"; -$in_min[eng] = "minutes"; -$verb_h[eng] = "interruption in conversation lasting more than an hour"; -$time_range_w[eng] = "Field \"From\" cannot be greater than field \"To\""; -$time_range_from[eng] = "from"; -$time_range_to[eng] = "to"; -$export_link[eng] = "export"; -$export_head1[eng] = "Exported chat between you and "; -$export_head2[eng] = "performed on"; -$help_search_tips[eng] =" -

-
  • Search Tips
  • -
      When searching you can do some more complex queries like:
      - if you want to find all chats from particular user you can type:
      - from:jid@example.com - where jid is user name of the server: example.com
      - or if you want to find phase in chats with that user, you can type:
      - from:jid@example.com:what is jabber - witch will query for phase what is jabber in all chats with user jid@example.com
      - Search engine also of course supports normal search that search all archives:
      - what is jabber - will search in all our chats phase \"what is jabber\" as well as all keywords like: \"what\", \"is\", \"jabber\"
      - If we don't know full name that we are searching we can put instead character: * (wildcard):
      - wor* - will find all words that begin with wor* like: word, work, world... -
    -"; -$help_my_links_note[eng] = " -

    -
  • MyLinks: overview.
  • -
      MyLinks let you store your favorited links. Thanks to MyLinks option you can easly and fast find your favorited talk.
      -To add chat to MyLinks just click on the right side of the chat window onto option called \"save in mylinks\". Then fill the form with description and save link into database. -
    - - - - -"; -$help_advanced_tips[eng] = " -

    -
  • How to search right
  • -
      Search engine of Jorge supports advanced mode called Boolean mode, that means that you can improve your search results.
      - Search engine search all your archives next it sort it and evaluates score and then displays only 100 most relevant matches.
      - To let you make it easy to adjust search results engine supports following arguments:
      - + - means that particular word must be in the results, so: +abc +def means that both words must be there
      - - - it excludes word from search results
      - > and < - increasese or decreases score for particular word
      - ( ) - make it possible to execute sub-query
      - ~ - adds negative score to particular word
      - * - replaces unknown word
      - \" - perform exact match search
      -
    - - -"; -$admin_site_gen[eng] = "Site generated in:"; -$logger_from_day[eng] = " from day: "; -$logger_overview[eng] = "Activity logs on Jorge"; -$logger_f1[eng] = "Event:"; -$logger_f2[eng] = "Event date:"; -$logger_f3[eng] = "Event level:"; -$logger_f4[eng] = "Additional info:"; -$logger_f_ip[eng] = "from IP address: "; -$refresh[eng] = "Refresh"; -$back_t[eng] = "Back to top of the page"; -$trash_name[eng] = "Trash"; -$trash_desc[eng] = "List of trashed conversations. Conversations that are left in trash are automaticly deleted after 30 days."; -$trash_undel[eng] = "Restore"; -$trash_vit[eng] = "View restored chat"; -$trash_del[eng] = "Delete"; -$trash_link[eng] = "Action"; -$trash_empty[eng] = "Trash is empty"; -$trash_recovered[eng] = "Conversation have been moved to archive"; -$cal_head[eng] = "Chat calendar"; -$cal_notice[eng] = "Click on days to see chats"; -$change_view[eng] = "Switch to tree view"; -$change_view_cal[eng] = "Browse archives using calendar view."; -$months_names = array("January","February","March","April","May","June","July","August","September","October","November","December"); -$weekdays = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); -$jump_to_l[eng] = "Select month"; -$chat_list_l[eng] = "Conversation list:"; -$select_view[eng] = "Select prefered view for browser:"; -$view_calendar[eng] = "Calendar view"; -$view_standard[eng] = "Tree view"; -$setting_d1[eng] = "Change global archivization policy:"; -$setting_d2[eng] = "Delete entire message archive (cannot undo):"; -$chat_map[eng] = "Chat map"; -$chat_select[eng] = "Select contact to see chats"; -$chat_m_select[eng] = "Pick a contact:"; -$chat_c_list[eng] = "Contacts list"; -$chat_no_chats[eng] = "There are no chats with selected contact"; -$chat_map_back[eng] = "<<< Back to ChatMap"; -$fav_back[eng] = "<<< Back to Favorites"; -$myl_back[eng] = "<<< Back to MyLinks"; -$sel_language[eng] = "Select prefered language"; -$sel_client[eng] = "Launch Slimster"; -$sel_yes[eng] = "Yes"; -$sel_no[eng] = "No"; -$jump_to_next[eng] = "Go to next conversation with this user"; -$jump_to_prev[eng] = "Go to to previous conversation with this user"; -$show_chats[eng] = "Show chat as"; -$show_chat_stream[eng] = "stream"; -$show_chat_as_map[eng] = "map"; -$tip_next_m[eng] = "Go to next month"; -$tip_prev_m[eng] = "Go to previous month"; -$cal_days[eng]['1'] = "Mon"; -$cal_days[eng]['2'] = "Tue"; -$cal_days[eng]['3'] = "Wed"; -$cal_days[eng]['4'] = "Thu"; -$cal_days[eng]['5'] = "Fri"; -$cal_days[eng]['6'] = "Sat"; -$cal_days[eng]['7'] = "Sun"; -$chat_lines[eng] = "Messages count: "; -$del_time[eng] = "Deleted:"; -$marked_as_d[eng] = "This chat is in trash. If you want to see it - restore it"; -$stats_personal_d[eng] = "Personal statistics"; -$stats_personal[eng] = "Your total number of messages in archiwe:"; -$stats_personal_top[eng] = "Your top 10 chats:"; -$stats_when[eng] = "When"; -$stats_personal_count[eng] = "Messages count"; -$stats_peer[eng] = "Talker"; -$stats_see[eng] = "See this chat"; -$stats_for[eng] = "Stats for: "; -$stats_messages[eng] = "Messages logged by server: "; -$stats_messages_b[eng] = " in "; -$stats_messages_c[eng] = " conversations."; -$stats_graph1[eng] = "Total number of users using message archiving (daily)"; -$stats_graph2[eng] = "Messages logged by server (daily)"; -$stats_graph3[eng] = "Messages logged (hourly)"; -$stats_graph4[eng] = "Messages logged (weekly)"; -$stats_top[eng] = "Longest conversations from last days:"; -$stats_not_eno[eng] = "Not enought data to plot the graphs (30 days needed)"; -$fav_main[eng] = "Favorites"; -$fav_desc[eng] = "List of chats marked as favorites"; -$fav_add[eng] = "Add conversation to favorites"; -$fav_chat[eng] = "Conversation with: "; -$fav_success[eng] = "Conversation has been succesfully added to your Favorites !"; -$fav_discard[eng] = "Discard this message"; -$fav_exist[eng] = "Ooops...This chat is already in your Favorites"; -$fav_favorited[eng] = "This conversation is already added to favorites"; -$fav_contact[eng] = "Conversation with:"; -$fav_when[eng] = "When:"; -$fav_comment[eng] = "Comment:"; -$fav_nocomm[eng] = "No comment"; -$fav_add_comment[eng] = "Add comment"; -$fav_remove[eng] = "delete"; -$fav_removed[eng] = "Conversation has been deleted from Favorites"; -$fav_empty[eng] = "You dont have any Favorites chats saved"; -$fav_error[eng] = "Oooups...There was a problem during processing your request"; -$reset_sort[eng] = "reset sorting"; -$cont_chat[eng] = "chat continues on next day >>>"; -$cont_chat_p[eng] = "<<< this chat is continuation from last day"; -$close_account[eng] = "Close your account:"; -$close_info[eng] = "WARNING: during account removal also account on Google Apps will be removed!"; -$close_warn[eng] = "Do you really want to remove all messages and user account?"; -$close_commit[eng] = "- Close now -"; -$close_failed[eng] = "Close account failed. Please try again later"; -$oper_fail[eng] = "
    Operation failed! Please try again later or contact administrator!
    "; -$go_to_jorge[eng] = "Go to Jorge main page"; -$qlink_l[eng] = "Go to latest conversations"; -$message_type_message[eng] = "Message"; -$message_type_error[eng] = "Message have been marked as faulty, and probably was not delivered."; -$message_type_headline[eng] = "Headline"; -$muc_message[eng] = "System message:"; -$spec_contact_enable[eng] = "Display special contact:"; -$spec_contact_desc[eng] = "This option let you decide if conversations with special contacts like gateways, transports are displayed in your chat list. Most users can say No here."; -$donate[eng] = "Help develop Project Jorge.Read More..."; -$donate_dont[eng] = "Don't show this information anymore..."; -$own_name_desc[eng] = "This option allows to display your name as you wish: f.e. james0021a is replaced with James"; -$own_name_enter[eng] = "Enter your name:"; -$own_name_commit[eng] = "Set your name"; -$own_name_remove[eng] = "If you dont want to use this option, leave it unchanged"; -$stats_vhost_select[eng] = "Select server for viewing its statistics: "; - -?> diff --git a/jorge/lang/pol.php b/jorge/lang/pol.php deleted file mode 100644 index 3d96b9b..0000000 --- a/jorge/lang/pol.php +++ /dev/null @@ -1,330 +0,0 @@ - - UWAGA: System jest w trakcie testów co oznacza że może nie dziaÅ‚ac w ogóle, dziaÅ‚ać wadliwie lub narazić CiÄ™ na utratÄ™ danych. Używasz go na wÅ‚asnÄ… odpowiedzialność!"; -$welcome_1[pol] = "Jorge - archiwa rozmów. Zaloguj siÄ™ do systemu"; -$login_w[pol] = "Login"; -$passwd_w[pol] = "HasÅ‚o"; -$login_act[pol] = "Zaloguj siÄ™"; -$devel_info[pol] = "Wersja BETA"; -$activate_m[pol] = "AKTYWUJ"; -$ch_lan[pol] = "ZmieÅ„ jÄ™zyk na:"; -$ch_lan2[pol] = "Change language to "; -$lang_sw[pol] = "English"; -$lang_sw2[pol] = "English"; -$header_l[pol] = "Archiwa rozmów serwera"; -$menu_item_browser[pol] = "PrzeglÄ…darka"; -$menu_item_map[pol] = "Mapa Rozmów"; -$menu_item_fav[pol] = "Ulubione"; -$menu_item_search[pol] = "Wyszukiwarka"; -$menu_item_links[pol] = "MyLinks"; -$menu_item_panel[pol] = "Panel Sterowania"; -$menu_item_contacts[pol] = "Kontakty"; -$menu_item_logs[pol] = "Logi"; -$menu_item_trash[pol] = "Kosz"; -$filter_form[pol] = "Filtruj listÄ™ kontaktów *"; -$filter_form_tip[pol] = "Wpisz nazwÄ™ kontaktu"; -$filter_tip[pol] = "...a nastÄ™pnie wybierz z listy, lub przeszukaj listÄ™ rÄ™cznie:"; -$ff_notice[pol] = "Ta opcja dziaÅ‚a tylko w przeglÄ…darce Firefox"; -$search_box[pol] = "Szukaj w archiwach"; -$search_tip[pol] = "WyÅ›wietlam"; -$search_why[pol] = " wyników (nie wiÄ™cej niż 100). Dowiedz siÄ™ dlaczego"; -$search_warn[pol] = "Uwaga: Wyszukuje tylko w wybranym przedziale czasu"; -$all_for_u[pol] = "Pokaż wszystkie rozmowy używajÄ…c: "; -$all_for_u_m[pol] = "strumienia"; -$all_for_u_m_d[pol] = "Pokaż wszystkie rozmowy z tÄ… osobÄ… jako strumieÅ„ wiadomoÅ›ci"; -$all_for_u_m2[pol] = "mapy"; -$all_for_u_m2_d[pol] = "Pokaż wszystkie rozmowy z tÄ… osobÄ… jako mapÄ™ rozmów"; -$all_for_u_t[pol] = "Pokaż wszystkie rozmowy z tym użytkownikiem"; -$arch_on[pol] = "WÅ‚Ä…cz archiwizacje"; -$arch_off[pol] = "WyÅ‚Ä…cz archiwizacje"; -$log_out_b[pol] = "Wyloguj"; -$archives_t[pol] = "PrzeglÄ…darka archiwum"; -$main_date[pol] = "Data:"; -$talks[pol] = "Lista rozmów:"; -$thread[pol] = "Treść:"; -$time_t[pol] = "Czas:"; -$user_t[pol] = "Użytkownik:"; -$my_links_save[pol] = "MyLinks"; -$my_links_desc_m[pol] = "MyLinks - Twoje linki"; -$my_links_desc_e[pol] = "Tutaj znajdziesz listÄ™ zapisanych fragmentów rozmów"; -$settings_desc[pol] = "Ustawienia archiwum"; -$settings_desc_detail[pol] = "Panel zawiera opcje pozwalajÄ…ce kontrolować archiwizacje rozmów oraz opcje dotyczÄ…ce konta"; -$api_access_enable[pol] = "WÅ‚Ä…cz publiczne API dla tego konta"; -$api_access_disable[pol] = "WyÅ‚Ä…cz publiczne API dla tego konta"; -$api_access_on[pol] = "API dla tego konta jest wÅ‚Ä…czone"; -$api_access_learn[pol] = "Dowiedz siÄ™ wiÄ™cej na temat publicznego API"; -$print_t[pol] = "drukuj"; -$del_t[pol] = "usuÅ„"; -$resource_only[pol] = "Pokaż rozmowÄ™ tylko z tym zasobem"; -$resource_warn[pol] = "PokazujÄ™ rozmowÄ™ z zasobem: "; -$resource_discard[pol] = "Pokaż "; -$resource_discard2[pol] = "caÅ‚Ä… rozmowÄ™."; -$del_all_conf[pol] = "Czy napewno chcesz usunąć *CAÅE* swoje archiwum wiadomoÅ›ci?\\nUWAGA: Nie bÄ™dzie możliwoÅ›ci przywrócenia archiwum!"; -$deleted_all[pol] = "CaÅ‚e Twoje archiwum zostaÅ‚o usuniÄ™te"; -$delete_nothing[pol] = "Twoje archiwum jest puste. Nic nie usuniÄ™to"; -$delete_error[pol] = "Ooops...WystÄ…piÅ‚y bÅ‚Ä™dy podczas wykonywania polecenia. ProszÄ™ spróbować poźniej"; -$search_w1[pol] = "Wyszukiwany ciÄ…g nie może być krótszy niż 3 i dÅ‚uższy niż 70 znaków..."; -$search_res[pol] = "Wyniki wyszukiwania: "; -$my_links_save_d[pol] = "Zapisuje link. Wprowadź dane"; -$my_links_optional[pol] = "Opis (opcjonalne, max 120 znakow)"; -$my_links_chat[pol] = "Rozmowa z:"; -$my_links_commit[pol] = "zapisz"; -$my_links_cancel[pol] = "anuluj"; -$my_links_link[pol] = "Link z dnia:"; -$my_links_desc[pol] = "Opis:"; -$my_links_added[pol] = "Link zostaÅ‚ zapisany!"; -$my_links_back[pol] = "Wróć do rozmowy"; -$my_links_removed[pol] = "Link zostaÅ‚ usuniÄ™ty z bazy danych"; -$my_links_none[pol] = "Brak opisu"; -$status_msg1[pol] = "Archiwizacja rozmów jest aktualnie wyÅ‚Ä…czona"; -$status_msg2[pol] = "Archiwizacja zostaÅ‚a wÅ‚Ä…czona. (zmiany w profilu widoczne sÄ… po 10 sekundach)"; -$status_msg3[pol] = "Archiwizacja zostaÅ‚a wyÅ‚Ä…czona. (zmiany w profilu widoczne sÄ… po 10 sekundach)"; -$my_links_no_links[pol] = "Nie masz aktualnie zapisanych linków..."; -$quest1[pol] = "ZnalazÅ‚eÅ› bÅ‚Ä…d? ZgÅ‚oÅ› go!"; -$search1[pol] = "Szukaj..."; -$no_result[pol] = "Brak rezultatów wyszukiwania"; -$settings_del[pol] = "UsuÅ„ caÅ‚e archiwum"; -$del_conf[pol] = "Czy na pewno usunąć tÄ… rozmowÄ™?"; -$del_conf_my_link[pol] = "Czy na pewno usunąć ten link?"; -$not_in_r[pol] = "Kontakt specjalny"; -$del_moved[pol] = "Rozmowa zostaÅ‚a przeniesiona do kosza."; -$del_info[pol] = "Rozmowa zostaÅ‚a usuniÄ™ta"; -$undo_info[pol] = "Rozmowa zostaÅ‚a przywrócona"; -$del_my_link[pol] = "usuÅ„"; -$help_but[pol] = "Pomoc"; -$tip_delete[pol] = "UsuÅ„ historiÄ™ rozmowy z tego dnia"; -$tip_export[pol] = "Eksportuj rozmowÄ™ do pliku tekstowego"; -$customize1[pol] = "Dostosuj logowanie"; -$from_u[pol] = "Od: "; -$to_u[pol] = "Do: "; -$search_next[pol] = "NastÄ™pne wyniki..."; -$search_prev[pol] = "Poprzednie wyniki..."; -$change_pass[pol] = "ZmieÅ„ hasÅ‚o"; -$no_contacts[pol] = "Brak kontaktów na liÅ›cie"; -$no_archives[pol] = "W tej chwili nie masz zapisanych żadnych rozmów"; -$con_tab1[pol] = "Lp."; -$con_tab2[pol] = "Nazwa kontaktu"; -$con_tab3[pol] = "JabberID"; -$con_tab4[pol] = "WÅ‚Ä…czyć archiwizacje"; -$con_tab_act_y[pol] = "Tak"; -$con_tab_act_n[pol] = "Nie"; -$con_tab_submit[pol] = "Zapisz zmiany"; -$con_tab6[pol] = "Grupa"; -$con_no_g[pol] = "Brak grupy"; -$map_no_g[pol] = "brak grupy"; -$con_head[pol] = "ZarzÄ…dzanie kontaktami"; -$con_notice[pol] = "Uwaga: wyÅ›wietlane sÄ… tylko kontakty z przypisanÄ… nazwÄ… kontaktu."; -$con_title[pol] = "Kliknij na kontakcie aby zobaczyć archiwum rozmów"; -$con_saved[pol] = "Zmiany zostaÅ‚y zapisane"; -$help_notice[pol] = "Główne zagadnienia"; -$nx_dy[pol] = "Kolejny dzieÅ„"; -$no_more[pol] = "Brak wiÄ™kszej iloÅ›ci wyników"; -$in_min[pol] = "minut"; -$verb_h[pol] = "przerwa w rozmowie trwajÄ…ca ponad godzinÄ™"; -$time_range_w[pol] = "Pole \"Od\" nie może być wiÄ™ksze od pola \"Do\""; -$time_range_from[pol] = "od"; -$time_range_to[pol] = "do"; -$export_link[pol] = "eksportuj"; -$export_head1[pol] = "Historia rozmowy miÄ™dzy TobÄ… a "; -$export_head2[pol] = "przeprowadzona w dniu"; -$help_search_tips[pol] = " -

    -
  • Wyszukiwarka: Podpowiedzi.
  • -
      Przeszukując archiwa można zadawać kilka rodzajów zapytań na przykład:
      - żeby znaleźć wszystkie rozmowy z danym użytkownikiem wpisujemy w oknie wyszukiwania:
      - from:jid@przykład.pl - gdzie jid to nazwa użytkownika, a przykład.pl to serwer na którym wyszukiwana osoba ma konto.
      - aby wyszukać daną frazę w rozmowie z użytkownikiem możemy wykonać następujące zapytanie:
      - from:jid@przykład.pl:co to jest jabber - takie zapytanie przeszuka wszystkie rozmowy z użytkownikem jid z serwera przykład.pl w poszukiwaniu frazy: co to jest jabber
      - Wyszukiwarka obsługuje oczywiście zwykłe wyszukiwanie - we wszystkich przeprowadzonych przez nas rozmowach:
      - co to jest jabber - wyszuka we wszystkich rozmowach frazy \"co to jest jabber\" jak również wyświetli wszystkie linie rozmowy zawierające słowa kluczowe
      - Jeśli nie znamy pełnej nazwy której poszukijemy możemy daną/dane litery zastąpić znakiem: * (gwiazdka) np.:
      - jak* - znajdzie wszystkie słowa zaczynające się na jak czyli np. jaki, jaka - - -
    - -"; -$help_my_links_note[pol] = " -

    -
  • MyLinks: informacje ogólne.
  • -
      MyLinks służy do przechowywania(zapamiętywania) ulubionych fragmentów rozmów. Dzieki opcji MyLinks można w łatwy i szybki sposób odnaleźć poszukiwaną rozmowę.
      -Aby dodać daną rozmowę do MyLinks należy kliknąć po prawej stronie okna z wyszukiwaną rozmową na opcji \"zapisz w mylinks\". Po wprowadzeniu opisu, link zostanie
      -zapisany w zakładce MyLinks. -
    - -"; -$help_advanced_tips[pol] = " -

    -
  • Jak szukać dokÅ‚adnie?
  • -
      Wyszukiwarga Jorge obsługuje zaawansowane tryby wyszukiwania tzw. Boolean mode, co oznacza że znacznie można poprawić rezultaty wyszukiwania.
      - Wyszukiwarka przeszukuje wszystkie Twoje archiwa w poszukiwaniu danej frazy, następnie ocenia tzw. \"score\", sortuje dane i wyświetla najlepiej pasujące 100 wyników
      - Aby ułatwić wyszukiwanie możesz użyć następujących modyfikatorów:
      - + - oznacza że dane słowo musi znaleźć się w wynikach wyszukiwania np. (+abc +def - odszuka wszystkie rozmowy zawierające w danej lini abc oraz def)
      - - - oznacza że dane słowo ma nie występować w wynikach wyszukiwania
      - > oraz < - nadaje dodatkowe punkty wyszukiwanemu słowu w frazie. Np. poszukując linka wiemy że zawieta http i np. słowo planeta. Aby zwiększyć trafność wyników zapytanie powinno wyglądać tak: \"http <planeta\"
      - ( ) - oznacza wykonanie pod-zapytania
      - ~ - dodaje negatywne punkty do danego słowa - ale go nie wyklucza z wyników
      - * - zastępuje ciąg znaków
      - \" - oznacza wyszukiwanie dokładnie pasującej frazy np: \"jak to\" znajdzie tylko rozmowy z dokładnie tą frazą - -
    - -"; -$admin_site_gen[pol] = "Strona została wygenerowana w: "; -$logger_from_day[pol] = " z dnia: "; -$logger_overview[pol] = "Logi aktywności w Jorge"; -$logger_f1[pol] = "Zdarzenie:"; -$logger_f2[pol] = "Data zdarzenia:"; -$logger_f3[pol] = "Poziom zdarzenia:"; -$logger_f4[pol] = "Dodatkowe informacje:"; -$logger_f_ip[pol] = "z adresu IP: "; -$refresh[pol] = "Odśwież"; -$back_t[pol] = "Wróć na góre strony"; -$trash_name[pol] = "Kosz"; -$trash_desc[pol] = "Lista rozmów usuniętych. Wiadomości które przebywają w koszu dłużej niż 30 dni są automatycznie usuwane"; -$trash_undel[pol] = "Przywróć"; -$trash_vit[pol] = "Zobacz przywróconą rozmowę"; -$trash_del[pol] = "Usuń"; -$trash_link[pol] = "Akcja"; -$trash_empty[pol] = "Kosz jest pusty"; -$trash_recovered[pol] = "Rozmowa została przeniesiona do archiwum"; -$cal_head[pol] = "Kalendarz rozmów."; -$cal_notice[pol] = "Kliknij na danym dniu aby zobaczyć rozmowy"; -$change_view[pol] = "Zmień na widok drzewa"; -$change_view_cal[pol] = "Przeglądaj archiwum za pomocą widoku kalendarza."; -$months_names = array("Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień"); -$weekdays = array("Poniedziałek","Wtorek","Środa","Czwartek","Piątek","Sobota","Niedziela"); -$jump_to_l[pol] = "Wybierz miesiąc"; -$chat_list_l[pol] = "Lista rozmów:"; -$select_view[pol] = "Wybierz rodzaj widoku przeglądarki:"; -$view_calendar[pol] = "Widok kalendarza"; -$view_standard[pol] = "Widok drzewa"; -$setting_d1[pol] = "Zmień globalną opcję archiwizacji:"; -$setting_d2[pol] = "Usuń całe archiwum wiadomości (nie można wycofać):"; -$chat_map[pol] = "Mapa rozmów"; -$chat_select[pol] = "Wybierz kontakt aby zobaczyć listę rozmów"; -$chat_m_select[pol] = "Wybierz kontakt:"; -$chat_c_list[pol] = "Lista kontaktów"; -$chat_no_chats[pol] = "Brak rozmów z wybranym kontaktem"; -$chat_map_back[pol] = "<<< Wróć do Mapy Rozmów"; -$fav_back[pol] = "<<< Wróć do Ulubionych"; -$myl_back[pol] = "<<< Wróć do MyLinks"; -$sel_language[pol] = "Wybierz preferowany język"; -$sel_client[pol] = "Uruchom Slimster"; -$sel_yes[pol] = "Tak"; -$sel_no[pol] = "Nie"; -$jump_to_next[pol] = "Przejdź do następnego dnia rozmowy"; -$jump_to_prev[pol] = "Przejdź do poprzedniego dnia rozmowy"; -$show_chats[pol] = "Pokaż rozmowę jako"; -$show_chat_stream[pol] = "strumień"; -$show_chat_as_map[pol] = "mapę"; -$tip_next_m[pol] = "Przejdź do następnego miesiąca"; -$tip_prev_m[pol] = "Przejdź do poprzedniego miesiąca"; -$cal_days[pol]['1'] = "Pon"; -$cal_days[pol]['2'] = "Wto"; -$cal_days[pol]['3'] = "Śro"; -$cal_days[pol]['4'] = "Czw"; -$cal_days[pol]['5'] = "Pią"; -$cal_days[pol]['6'] = "Sob"; -$cal_days[pol]['7'] = "Nie"; -$chat_lines[pol] = "Ilość wiadomości: "; -$del_time[pol] = "Usunięto:"; -$marked_as_d[pol] = "Ta rozmowa znajduje się w koszu. Aby ją przeglądać musisz ją przywrócić"; -$stats_personal_d[pol] = "Statystyki rozmów"; -$stats_personal[pol] = "Twoja całkowita liczba wiadomości w archiwum:"; -$stats_personal_top[pol] = "10 najdłuższych rozmów:"; -$stats_when[pol] = "Kiedy"; -$stats_personal_count[pol] = "Liczba wiadomości"; -$stats_peer[pol] = "Rozmówca"; -$stats_see[pol] = "Zobacz rozmowę"; -$stats_for[pol] = "Statystyki dla: "; -$stats_messages[pol] = "Serwer zalogował "; -$stats_messages_b[pol] = " wiadomości w "; -$stats_messages_c[pol] = " rozmowach."; -$stats_graph1[pol] = "Całkowita liczba użytkowników korzystających z archiwizacji (dziennie)"; -$stats_graph2[pol] = "Ilość wiadomości zalogowanych przez serwer (dziennie)"; -$stats_graph3[pol] = "Zalogowane wiadomości (godzinowo)"; -$stats_graph4[pol] = "Zalogowane wiadomości (tygodniowo)"; -$stats_top[pol] = "Najdłuższe rozmowy z ostatnich dni:"; -$stats_not_eno[pol] = "Brak wystarczających danych do narysowania statystyk (minimum 30 dni)"; -$fav_main[pol] = "Ulubione"; -$fav_desc[pol] = "Lista rozmów oznaczonych jako \"Ulubione\""; -$fav_add[pol] = "Dodaj rozmowę do ulubionych"; -$fav_chat[pol] = "Rozmowa z: "; -$fav_success[pol] = "Rozmowa została dodana do Twoich Ulubionych !"; -$fav_discard[pol] = "Ukryj tą informacje"; -$fav_exist[pol] = "Ooops...Ta rozmowa juz znajduje się w Twoich Ulubionych"; -$fav_favorited[pol] = "Ta rozmowa jest dodana do ulubionych"; -$fav_contact[pol] = "Rozmowa z:"; -$fav_when[pol] = "Kiedy:"; -$fav_comment[pol] = "Komentarz:"; -$fav_nocomm[pol] = "Brak komentarza"; -$fav_add_comment[pol] = "Dodaj komentarz"; -$fav_remove[pol] = "usuń"; -$fav_removed[pol] = "Rozmowa została usnięta z Ulubionych"; -$fav_empty[pol] = "Nie masz aktualnie zapisanych żadnych Ulubionych rozmów"; -$fav_error[pol] = "Oooups...Wystąpił błąd podczas dodawania rozmowy"; -$reset_sort[pol] = "resetuj sortowanie"; -$cont_chat[pol] = "rozmowa kontynuowana jest następnego dnia >>>"; -$cont_chat_p[pol] = "<<< rozmowa jest kontynuacją z dnia poprzedniego"; -$close_account[pol] = "Usuń konto z serwera:"; -$close_info[pol] = "UWAGA: wraz z kontem XMPP zostanie usunięte konto z Google Apps!"; -$close_warn[pol] = "Czy napewno usunąć konto i wszystkie wiadomości?"; -$close_commit[pol] = "- Usuń teraz -"; -$close_failed[pol] = "Usunięcie konta nie powiodło się. Proszę spróbować później"; -$oper_fail[pol] = "
    Operacja nie została wykonana! Proszę spróbować później lub skontaktować się z administratorem!
    "; -$go_to_jorge[pol] = "Idz do strony glownej"; -$qlink_l[pol] = "Przejdź do najnowszych rozmów"; -$message_type_message[pol] = "Wiadomość"; -$message_type_error[pol] = "Wiadomość została oznaczona jako zawierająca błąd i prawdopodobnie nie została dostarczona."; -$message_type_headline[pol] = "Headline"; -$muc_message[pol] = "Wiadomość systemowa:"; -$spec_contact_enable[pol] = "Wyświetlać kontakty specjalne:"; -$spec_contact_desc[pol] = "Pozwala zdecydować czy w liście rozmów mają pojawiać się rozmowy z kontaktami specjalnymi np.: bramkami lub transportami. Większość użytkowników może spokojnie tą opcje wyłączyć"; -$donate[pol] = "Pomóż rozwijać Projekt Jorge.Przeczytaj więcej..."; -$donate_dont[pol] = "Nie pokazuj tej informacji więcej..."; -$own_name_desc[pol] = "Opcja ta umożliwia zmianę wyświetlanej nazwy użytkownika: np. karol002a na Karol"; -$own_name_enter[pol] = "Podaj swoją nazwę:"; -$own_name_commit[pol] = "Ustaw nazwę"; -$own_name_remove[pol] = "Jeśli nie chcesz korzystać z tej opcji, pozostaw pole puste"; -$stats_vhost_select[pol] = "Wybierz serwer dla którego chcesz oglądać statystyki: "; - -?> diff --git a/jorge/lib/dimensions.js b/jorge/lib/dimensions.js deleted file mode 100644 index 92b232b..0000000 --- a/jorge/lib/dimensions.js +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) - * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. - * - * $LastChangedDate: 2007-03-27 23:29:43 +0200 (Di, 27 Mrz 2007) $ - * $Rev: 1601 $ - */ - -jQuery.fn._height = jQuery.fn.height; -jQuery.fn._width = jQuery.fn.width; - -/** - * If used on document, returns the document's height (innerHeight) - * If used on window, returns the viewport's (window) height - * See core docs on height() to see what happens when used on an element. - * - * @example $("#testdiv").height() - * @result 200 - * - * @example $(document).height() - * @result 800 - * - * @example $(window).height() - * @result 400 - * - * @name height - * @type Object - * @cat Plugins/Dimensions - */ -jQuery.fn.height = function() { - if ( this[0] == window ) - return self.innerHeight || - jQuery.boxModel && document.documentElement.clientHeight || - document.body.clientHeight; - - if ( this[0] == document ) - return Math.max( document.body.scrollHeight, document.body.offsetHeight ); - - return this._height(arguments[0]); -}; - -/** - * If used on document, returns the document's width (innerWidth) - * If used on window, returns the viewport's (window) width - * See core docs on height() to see what happens when used on an element. - * - * @example $("#testdiv").width() - * @result 200 - * - * @example $(document).width() - * @result 800 - * - * @example $(window).width() - * @result 400 - * - * @name width - * @type Object - * @cat Plugins/Dimensions - */ -jQuery.fn.width = function() { - if ( this[0] == window ) - return self.innerWidth || - jQuery.boxModel && document.documentElement.clientWidth || - document.body.clientWidth; - - if ( this[0] == document ) - return Math.max( document.body.scrollWidth, document.body.offsetWidth ); - - return this._width(arguments[0]); -}; - -/** - * Returns the inner height value (without border) for the first matched element. - * If used on document, returns the document's height (innerHeight) - * If used on window, returns the viewport's (window) height - * - * @example $("#testdiv").innerHeight() - * @result 800 - * - * @name innerHeight - * @type Number - * @cat Plugins/Dimensions - */ -jQuery.fn.innerHeight = function() { - return this[0] == window || this[0] == document ? - this.height() : - this.css('display') != 'none' ? - this[0].offsetHeight - (parseInt(this.css("borderTopWidth")) || 0) - (parseInt(this.css("borderBottomWidth")) || 0) : - this.height() + (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0); -}; - -/** - * Returns the inner width value (without border) for the first matched element. - * If used on document, returns the document's Width (innerWidth) - * If used on window, returns the viewport's (window) width - * - * @example $("#testdiv").innerWidth() - * @result 1000 - * - * @name innerWidth - * @type Number - * @cat Plugins/Dimensions - */ -jQuery.fn.innerWidth = function() { - return this[0] == window || this[0] == document ? - this.width() : - this.css('display') != 'none' ? - this[0].offsetWidth - (parseInt(this.css("borderLeftWidth")) || 0) - (parseInt(this.css("borderRightWidth")) || 0) : - this.height() + (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0); -}; - -/** - * Returns the outer height value (including border) for the first matched element. - * Cannot be used on document or window. - * - * @example $("#testdiv").outerHeight() - * @result 1000 - * - * @name outerHeight - * @type Number - * @cat Plugins/Dimensions - */ -jQuery.fn.outerHeight = function() { - return this[0] == window || this[0] == document ? - this.height() : - this.css('display') != 'none' ? - this[0].offsetHeight : - this.height() + (parseInt(this.css("borderTopWidth")) || 0) + (parseInt(this.css("borderBottomWidth")) || 0) - + (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0); -}; - -/** - * Returns the outer width value (including border) for the first matched element. - * Cannot be used on document or window. - * - * @example $("#testdiv").outerWidth() - * @result 1000 - * - * @name outerWidth - * @type Number - * @cat Plugins/Dimensions - */ -jQuery.fn.outerWidth = function() { - return this[0] == window || this[0] == document ? - this.width() : - this.css('display') != 'none' ? - this[0].offsetWidth : - this.height() + (parseInt(this.css("borderLeftWidth")) || 0) + (parseInt(this.css("borderRightWidth")) || 0) - + (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0); -}; - -/** - * Returns how many pixels the user has scrolled to the right (scrollLeft). - * Works on containers with overflow: auto and window/document. - * - * @example $("#testdiv").scrollLeft() - * @result 100 - * - * @name scrollLeft - * @type Number - * @cat Plugins/Dimensions - */ -jQuery.fn.scrollLeft = function() { - if ( this[0] == window || this[0] == document ) - return self.pageXOffset || - jQuery.boxModel && document.documentElement.scrollLeft || - document.body.scrollLeft; - - return this[0].scrollLeft; -}; - -/** - * Returns how many pixels the user has scrolled to the bottom (scrollTop). - * Works on containers with overflow: auto and window/document. - * - * @example $("#testdiv").scrollTop() - * @result 100 - * - * @name scrollTop - * @type Number - * @cat Plugins/Dimensions - */ -jQuery.fn.scrollTop = function() { - if ( this[0] == window || this[0] == document ) - return self.pageYOffset || - jQuery.boxModel && document.documentElement.scrollTop || - document.body.scrollTop; - - return this[0].scrollTop; -}; - -/** - * Returns the location of the element in pixels from the top left corner of the viewport. - * - * For accurate readings make sure to use pixel values for margins, borders and padding. - * - * @example $("#testdiv").offset() - * @result { top: 100, left: 100, scrollTop: 10, scrollLeft: 10 } - * - * @example $("#testdiv").offset({ scroll: false }) - * @result { top: 90, left: 90 } - * - * @example var offset = {} - * $("#testdiv").offset({ scroll: false }, offset) - * @result offset = { top: 90, left: 90 } - * - * @name offset - * @param Object options A hash of options describing what should be included in the final calculations of the offset. - * The options include: - * margin: Should the margin of the element be included in the calculations? True by default. - * If set to false the margin of the element is subtracted from the total offset. - * border: Should the border of the element be included in the calculations? True by default. - * If set to false the border of the element is subtracted from the total offset. - * padding: Should the padding of the element be included in the calculations? False by default. - * If set to true the padding of the element is added to the total offset. - * scroll: Should the scroll offsets of the parent elements be included in the calculations? - * True by default. When true, it adds the total scroll offsets of all parents to the - * total offset and also adds two properties to the returned object, scrollTop and - * scrollLeft. If set to false the scroll offsets of parent elements are ignored. - * If scroll offsets are not needed, set to false to get a performance boost. - * @param Object returnObject An object to store the return value in, so as not to break the chain. If passed in the - * chain will not be broken and the result will be assigned to this object. - * @type Object - * @cat Plugins/Dimensions - * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) - */ -jQuery.fn.offset = function(options, returnObject) { - var x = 0, y = 0, elem = this[0], parent = this[0], absparent=false, relparent=false, op, sl = 0, st = 0, options = jQuery.extend({ margin: true, border: true, padding: false, scroll: true }, options || {}); - do { - x += parent.offsetLeft || 0; - y += parent.offsetTop || 0; - - // Mozilla and IE do not add the border - if (jQuery.browser.mozilla || jQuery.browser.msie) { - // get borders - var bt = parseInt(jQuery.css(parent, 'borderTopWidth')) || 0; - var bl = parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0; - - // add borders to offset - x += bl; - y += bt; - - // Mozilla removes the border if the parent has overflow property other than visible - if (jQuery.browser.mozilla && parent != elem && jQuery.css(parent, 'overflow') != 'visible') { - x += bl; - y += bt; - } - - // Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent - if (jQuery.css(parent, 'position') == 'absolute') absparent = true; - // IE does not include the border on the body if an element is position static and without an absolute or relative parent - if (jQuery.css(parent, 'position') == 'relative') relparent = true; - } - - if (options.scroll) { - // Need to get scroll offsets in-between offsetParents - op = parent.offsetParent; - do { - sl += parent.scrollLeft || 0; - st += parent.scrollTop || 0; - - parent = parent.parentNode; - - // Mozilla removes the border if the parent has overflow property other than visible - if (jQuery.browser.mozilla && parent != elem && parent != op && jQuery.css(parent, 'overflow') != 'visible') { - x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0; - y += parseInt(jQuery.css(parent, 'borderTopWidth')) || 0; - } - } while (op && parent != op); - } else - parent = parent.offsetParent; - - if (parent && (parent.tagName.toLowerCase() == 'body' || parent.tagName.toLowerCase() == 'html')) { - // Safari and IE Standards Mode doesn't add the body margin for elments positioned with static or relative - if ((jQuery.browser.safari || (jQuery.browser.msie && jQuery.boxModel)) && jQuery.css(elem, 'position') != 'absolute') { - x += parseInt(jQuery.css(parent, 'marginLeft')) || 0; - y += parseInt(jQuery.css(parent, 'marginTop')) || 0; - } - // Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent - // IE does not include the border on the body if an element is positioned static and without an absolute or relative parent - if ( (jQuery.browser.mozilla && !absparent) || - (jQuery.browser.msie && jQuery.css(elem, 'position') == 'static' && (!relparent || !absparent)) ) { - x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0; - y += parseInt(jQuery.css(parent, 'borderTopWidth')) || 0; - } - break; // Exit the loop - } - } while (parent); - - if ( !options.margin) { - x -= parseInt(jQuery.css(elem, 'marginLeft')) || 0; - y -= parseInt(jQuery.css(elem, 'marginTop')) || 0; - } - - // Safari and Opera do not add the border for the element - if ( options.border && (jQuery.browser.safari || jQuery.browser.opera) ) { - x += parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0; - y += parseInt(jQuery.css(elem, 'borderTopWidth')) || 0; - } else if ( !options.border && !(jQuery.browser.safari || jQuery.browser.opera) ) { - x -= parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0; - y -= parseInt(jQuery.css(elem, 'borderTopWidth')) || 0; - } - - if ( options.padding ) { - x += parseInt(jQuery.css(elem, 'paddingLeft')) || 0; - y += parseInt(jQuery.css(elem, 'paddingTop')) || 0; - } - - // Opera thinks offset is scroll offset for display: inline elements - if (options.scroll && jQuery.browser.opera && jQuery.css(elem, 'display') == 'inline') { - sl -= elem.scrollLeft || 0; - st -= elem.scrollTop || 0; - } - - var returnValue = options.scroll ? { top: y - st, left: x - sl, scrollTop: st, scrollLeft: sl } - : { top: y, left: x }; - - if (returnObject) { jQuery.extend(returnObject, returnValue); return this; } - else { return returnValue; } -}; \ No newline at end of file diff --git a/jorge/lib/hl.js b/jorge/lib/hl.js deleted file mode 100644 index eae5611..0000000 --- a/jorge/lib/hl.js +++ /dev/null @@ -1,179 +0,0 @@ -/* - * This is the function that actually highlights a text string by - * adding HTML tags before and after all occurrences of the search - * term. You can pass your own tags if you'd like, or if the - * highlightStartTag or highlightEndTag parameters are omitted or - * are empty strings then the default tags will be used. - */ -function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) -{ - // the highlightStartTag and highlightEndTag parameters are optional - if ((!highlightStartTag) || (!highlightEndTag)) { - highlightStartTag = ""; - highlightEndTag = ""; - } - - // find all occurences of the search term in the given text, - // and add some "highlight" tags to them (we're not using a - // regular expression search, because we want to filter out - // matches that occur within HTML tags and script blocks, so - // we have to do a little extra validation) - var newText = ""; - var i = -1; - var lcSearchTerm = searchTerm.toLowerCase(); - var lcBodyText = bodyText.toLowerCase(); - - while (bodyText.length > 0) { - i = lcBodyText.indexOf(lcSearchTerm, i+1); - if (i < 0) { - newText += bodyText; - bodyText = ""; - } else { - // skip anything inside an HTML tag - if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) { - // skip anything inside a diff --git a/jorge/lib/jquery.autocomplete.pack.js b/jorge/lib/jquery.autocomplete.pack.js deleted file mode 100644 index 271014a..0000000 --- a/jorge/lib/jquery.autocomplete.pack.js +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Autocomplete - jQuery plugin 1.0.2 - * - * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer - * - * Dual licensed under the MIT and GPL licenses: - * http://www.opensource.org/licenses/mit-license.php - * http://www.gnu.org/licenses/gpl.html - * - * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $ - * - */ -eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(3($){$.31.1o({12:3(b,d){5 c=Y b=="1w";d=$.1o({},$.D.1L,{11:c?b:14,w:c?14:b,1D:c?$.D.1L.1D:10,Z:d&&!d.1x?10:3U},d);d.1t=d.1t||3(a){6 a};d.1q=d.1q||d.1K;6 I.K(3(){1E $.D(I,d)})},M:3(a){6 I.X("M",a)},1y:3(a){6 I.15("1y",[a])},20:3(){6 I.15("20")},1Y:3(a){6 I.15("1Y",[a])},1X:3(){6 I.15("1X")}});$.D=3(o,r){5 t={2N:38,2I:40,2D:46,2x:9,2v:13,2q:27,2d:3x,2j:33,2o:34,2e:8};5 u=$(o).3f("12","3c").P(r.24);5 p;5 m="";5 n=$.D.2W(r);5 s=0;5 k;5 h={1z:B};5 l=$.D.2Q(r,o,1U,h);5 j;$.1T.2L&&$(o.2K).X("3S.12",3(){4(j){j=B;6 B}});u.X(($.1T.2L?"3Q":"3N")+".12",3(a){k=a.2F;3L(a.2F){Q t.2N:a.1d();4(l.L()){l.2y()}A{W(0,C)}N;Q t.2I:a.1d();4(l.L()){l.2u()}A{W(0,C)}N;Q t.2j:a.1d();4(l.L()){l.2t()}A{W(0,C)}N;Q t.2o:a.1d();4(l.L()){l.2s()}A{W(0,C)}N;Q r.19&&$.1p(r.R)==","&&t.2d:Q t.2x:Q t.2v:4(1U()){a.1d();j=C;6 B}N;Q t.2q:l.U();N;3A:1I(p);p=1H(W,r.1D);N}}).1G(3(){s++}).3v(3(){s=0;4(!h.1z){2k()}}).2i(3(){4(s++>1&&!l.L()){W(0,C)}}).X("1y",3(){5 c=(1n.7>1)?1n[1]:14;3 23(q,a){5 b;4(a&&a.7){16(5 i=0;i1){v=a.17(0,a.7-1).2Z(r.R)+r.R+v}v+=r.R}u.J(v);1l();u.15("M",[b.w,b.H]);6 C}3 W(b,c){4(k==t.2D){l.U();6}5 a=u.J();4(!c&&a==m)6;m=a;a=1k(a);4(a.7>=r.22){u.P(r.21);4(!r.1C)a=a.O();1R(a,2V,1l)}A{1B();l.U()}};3 1g(b){4(!b){6[""]}5 d=b.1Z(r.R);5 c=[];$.K(d,3(i,a){4($.1p(a))c[i]=$.1p(a)});6 c}3 1k(a){4(!r.19)6 a;5 b=1g(a);6 b[b.7-1]}3 1A(q,a){4(r.1A&&(1k(u.J()).O()==q.O())&&k!=t.2e){u.J(u.J()+a.48(1k(m).7));$.D.1N(o,m.7,m.7+a.7)}};3 2k(){1I(p);p=1H(1l,47)};3 1l(){5 c=l.L();l.U();1I(p);1B();4(r.2U){u.1y(3(a){4(!a){4(r.19){5 b=1g(u.J()).17(0,-1);u.J(b.2Z(r.R)+(b.7?r.R:""))}A u.J("")}})}4(c)$.D.1N(o,o.H.7,o.H.7)};3 2V(q,a){4(a&&a.7&&s){1B();l.2T(a,q);1A(q,a[0].H);l.1W()}A{1l()}};3 1R(f,d,g){4(!r.1C)f=f.O();5 e=n.2S(f);4(e&&e.7){d(f,e)}A 4((Y r.11=="1w")&&(r.11.7>0)){5 c={45:+1E 44()};$.K(r.2R,3(a,b){c[a]=Y b=="3"?b():b});$.43({42:"41",3Z:"12"+o.3Y,2M:r.2M,11:r.11,w:$.1o({q:1k(f),3X:r.Z},c),3W:3(a){5 b=r.1r&&r.1r(a)||1r(a);n.1h(f,b);d(f,b)}})}A{l.2J();g(f)}};3 1r(c){5 d=[];5 b=c.1Z("\\n");16(5 i=0;i]*)("+a.2C(/([\\^\\$\\(\\)\\[\\]\\{\\}\\*\\.\\+\\?\\|\\\\])/2A,"\\\\$1")+")(?![^<>]*>)(?![^&;]+;)","2A"),"<2z>$1")},1x:C,1s:3I};$.D.2W=3(g){5 h={};5 j=0;3 1a(s,a){4(!g.1C)s=s.O();5 i=s.3H(a);4(i==-1)6 B;6 i==0||g.1V};3 1h(q,a){4(j>g.1j){18()}4(!h[q]){j++}h[q]=a}3 1f(){4(!g.w)6 B;5 f={},2w=0;4(!g.11)g.1j=1;f[""]=[];16(5 i=0,30=g.w.7;i<30;i++){5 c=g.w[i];c=(Y c=="1w")?[c]:c;5 d=g.1q(c,i+1,g.w.7);4(d===B)1P;5 e=d.3G(0).O();4(!f[e])f[e]=[];5 b={H:d,w:c,M:g.1v&&g.1v(c)||d};f[e].1O(b);4(2w++0){5 c=h[k];$.K(c,3(i,x){4(1a(x.H,q)){a.1O(x)}})}}6 a}A 4(h[q]){6 h[q]}A 4(g.1a){16(5 i=q.7-1;i>=g.22;i--){5 c=h[q.3F(0,i)];4(c){5 a=[];$.K(c,3(i,x){4(1a(x.H,q)){a[a.7]=x}});6 a}}}6 14}}};$.D.2Q=3(e,g,f,k){5 h={G:"3E"};5 j,y=-1,w,1m="",1M=C,F,z;3 2r(){4(!1M)6;F=$("<3D/>").U().P(e.2H).T("3C","3B").1J(2p.2n);z=$("<3z/>").1J(F).3y(3(a){4(V(a).2m&&V(a).2m.3w()==\'2l\'){y=$("1F",z).1e(h.G).3u(V(a));$(V(a)).P(h.G)}}).2i(3(a){$(V(a)).P(h.G);f();g.1G();6 B}).3t(3(){k.1z=C}).3s(3(){k.1z=B});4(e.E>0)F.T("E",e.E);1M=B}3 V(a){5 b=a.V;3r(b&&b.3q!="2l")b=b.3p;4(!b)6[];6 b}3 S(b){j.17(y,y+1).1e(h.G);2h(b);5 a=j.17(y,y+1).P(h.G);4(e.1x){5 c=0;j.17(0,y).K(3(){c+=I.1i});4((c+a[0].1i-z.1c())>z[0].3o){z.1c(c+a[0].1i-z.3n())}A 4(c=j.1b()){y=0}}3 2g(a){6 e.Z&&e.Z").3m(e.1t(a,1m)).P(i%2==0?"3l":"3k").1J(z)[0];$.w(c,"2c",w[i])}j=z.3j("1F");4(e.1S){j.17(0,1).P(h.G);y=0}4($.31.2b)z.2b()}6{2T:3(d,q){2r();w=d;1m=q;2f()},2u:3(){S(1)},2y:3(){S(-1)},2t:3(){4(y!=0&&y-8<0){S(-y)}A{S(-8)}},2s:3(){4(y!=j.1b()-1&&y+8>j.1b()){S(j.1b()-1-y)}A{S(8)}},U:3(){F&&F.U();j&&j.1e(h.G);y=-1},L:3(){6 F&&F.3i(":L")},3h:3(){6 I.L()&&(j.2a("."+h.G)[0]||e.1S&&j[0])},1W:3(){5 a=$(g).3g();F.T({E:Y e.E=="1w"||e.E>0?e.E:$(g).E(),2E:a.2E+g.1i,1Q:a.1Q}).1W();4(e.1x){z.1c(0);z.T({29:e.1s,3e:\'3d\'});4($.1T.3b&&Y 2p.2n.3T.29==="3a"){5 c=0;j.K(3(){c+=I.1i});5 b=c>e.1s;z.T(\'3V\',b?e.1s:c);4(!b){j.E(z.E()-28(j.T("32-1Q"))-28(j.T("32-39")))}}}},26:3(){5 a=j&&j.2a("."+h.G).1e(h.G);6 a&&a.7&&$.w(a[0],"2c")},2J:3(){z&&z.2B()},1u:3(){F&&F.37()}}};$.D.1N=3(b,a,c){4(b.2O){5 d=b.2O();d.36(C);d.35("2P",a);d.4c("2P",c);d.4b()}A 4(b.2Y){b.2Y(a,c)}A{4(b.2X){b.2X=a;b.4a=c}}b.1G()}})(49);',62,261,'|||function|if|var|return|length|||||||||||||||||||||||||data||active|list|else|false|true|Autocompleter|width|element|ACTIVE|value|this|val|each|visible|result|break|toLowerCase|addClass|case|multipleSeparator|moveSelect|css|hide|target|onChange|bind|typeof|max||url|autocomplete||null|trigger|for|slice|flush|multiple|matchSubset|size|scrollTop|preventDefault|removeClass|populate|trimWords|add|offsetHeight|cacheLength|lastWord|hideResultsNow|term|arguments|extend|trim|formatMatch|parse|scrollHeight|highlight|unbind|formatResult|string|scroll|search|mouseDownOnSelect|autoFill|stopLoading|matchCase|delay|new|li|focus|setTimeout|clearTimeout|appendTo|formatItem|defaults|needsInit|Selection|push|continue|left|request|selectFirst|browser|selectCurrent|matchContains|show|unautocomplete|setOptions|split|flushCache|loadingClass|minChars|findValueCallback|inputClass||selected||parseInt|maxHeight|filter|bgiframe|ac_data|COMMA|BACKSPACE|fillList|limitNumberOfItems|movePosition|click|PAGEUP|hideResults|LI|nodeName|body|PAGEDOWN|document|ESC|init|pageDown|pageUp|next|RETURN|nullData|TAB|prev|strong|gi|empty|replace|DEL|top|keyCode|in|resultsClass|DOWN|emptyList|form|opera|dataType|UP|createTextRange|character|Select|extraParams|load|display|mustMatch|receiveData|Cache|selectionStart|setSelectionRange|join|ol|fn|padding|||moveStart|collapse|remove||right|undefined|msie|off|auto|overflow|attr|offset|current|is|find|ac_odd|ac_even|html|innerHeight|clientHeight|parentNode|tagName|while|mouseup|mousedown|index|blur|toUpperCase|188|mouseover|ul|default|absolute|position|div|ac_over|substr|charAt|indexOf|180|RegExp|100|switch|400|keydown|ac_loading|ac_results|keypress|ac_input|submit|style|150|height|success|limit|name|port||abort|mode|ajax|Date|timestamp||200|substring|jQuery|selectionEnd|select|moveEnd'.split('|'),0,{})) \ No newline at end of file diff --git a/jorge/lib/jquery.bgiframe.min.js b/jorge/lib/jquery.bgiframe.min.js deleted file mode 100644 index 7faef4b..0000000 --- a/jorge/lib/jquery.bgiframe.min.js +++ /dev/null @@ -1,10 +0,0 @@ -/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net) - * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) - * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. - * - * $LastChangedDate: 2007-07-22 01:45:56 +0200 (Son, 22 Jul 2007) $ - * $Rev: 2447 $ - * - * Version 2.1.1 - */ -(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='
    - - - '; -} - - - - -/** - * A ReCaptchaResponse is returned from recaptcha_check_answer() - */ -class ReCaptchaResponse { - var $is_valid; - var $error; -} - - -/** - * Calls an HTTP POST function to verify if the user's guess was correct - * @param string $privkey - * @param string $remoteip - * @param string $challenge - * @param string $response - * @param array $extra_params an array of extra variables to post to the server - * @return ReCaptchaResponse - */ -function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) -{ - if ($privkey == null || $privkey == '') { - die ("To use reCAPTCHA you must get an API key from http://recaptcha.net/api/getkey"); - } - - if ($remoteip == null || $remoteip == '') { - die ("For security reasons, you must pass the remote ip to reCAPTCHA"); - } - - - - //discard spam submissions - if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { - $recaptcha_response = new ReCaptchaResponse(); - $recaptcha_response->is_valid = false; - $recaptcha_response->error = 'incorrect-captcha-sol'; - return $recaptcha_response; - } - - $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/verify", - array ( - 'privatekey' => $privkey, - 'remoteip' => $remoteip, - 'challenge' => $challenge, - 'response' => $response - ) + $extra_params - ); - - $answers = explode ("\n", $response [1]); - $recaptcha_response = new ReCaptchaResponse(); - - if (trim ($answers [0]) == 'true') { - $recaptcha_response->is_valid = true; - } - else { - $recaptcha_response->is_valid = false; - $recaptcha_response->error = $answers [1]; - } - return $recaptcha_response; - -} - -/** - * gets a URL where the user can sign up for reCAPTCHA. If your application - * has a configuration page where you enter a key, you should provide a link - * using this function. - * @param string $domain The domain where the page is hosted - * @param string $appname The name of your application - */ -function recaptcha_get_signup_url ($domain = null, $appname = null) { - return "http://recaptcha.net/api/getkey?" . _recaptcha_qsencode (array ('domain' => $domain, 'app' => $appname)); -} - -function _recaptcha_aes_pad($val) { - $block_size = 16; - $numpad = $block_size - (strlen ($val) % $block_size); - return str_pad($val, strlen ($val) + $numpad, chr($numpad)); -} - -/* Mailhide related code */ - -function _recaptcha_aes_encrypt($val,$ky) { - if (! function_exists ("mcrypt_encrypt")) { - die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); - } - $mode=MCRYPT_MODE_CBC; - $enc=MCRYPT_RIJNDAEL_128; - $val=_recaptcha_aes_pad($val); - return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); -} - - -function _recaptcha_mailhide_urlbase64 ($x) { - return strtr(base64_encode ($x), '+/', '-_'); -} - -/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ -function recaptcha_mailhide_url($pubkey, $privkey, $email) { - if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { - die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . - "you can do so at http://mailhide.recaptcha.net/apikey"); - } - - - $ky = pack('H*', $privkey); - $cryptmail = _recaptcha_aes_encrypt ($email, $ky); - - return "http://mailhide.recaptcha.net/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); -} - -/** - * gets the parts of the email to expose to the user. - * eg, given johndoe@example,com return ["john", "example.com"]. - * the email is then displayed as john...@example.com - */ -function _recaptcha_mailhide_email_parts ($email) { - $arr = preg_split("/@/", $email ); - - if (strlen ($arr[0]) <= 4) { - $arr[0] = substr ($arr[0], 0, 1); - } else if (strlen ($arr[0]) <= 6) { - $arr[0] = substr ($arr[0], 0, 3); - } else { - $arr[0] = substr ($arr[0], 0, 4); - } - return $arr; -} - -/** - * Gets html to display an email address given a public an private key. - * to get a key, go to: - * - * http://mailhide.recaptcha.net/apikey - */ -function recaptcha_mailhide_html($pubkey, $privkey, $email) { - $emailparts = _recaptcha_mailhide_email_parts ($email); - $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); - - return htmlentities($emailparts[0]) . "...@" . htmlentities ($emailparts [1]); - -} - - -?> diff --git a/jorge/lib/simpletreemenu.js b/jorge/lib/simpletreemenu.js deleted file mode 100644 index f5a770f..0000000 --- a/jorge/lib/simpletreemenu.js +++ /dev/null @@ -1,133 +0,0 @@ -var persisteduls=new Object() -var ddtreemenu=new Object() - -ddtreemenu.closefolder="img/closed.png" //set image path to "closed" folder image -ddtreemenu.openfolder="img/open.png" //set image path to "open" folder image - -//////////No need to edit beyond here/////////////////////////// - -ddtreemenu.createTree=function(treeid, enablepersist, persistdays){ -var ultags=document.getElementById(treeid).getElementsByTagName("ul") -if (typeof persisteduls[treeid]=="undefined") -persisteduls[treeid]=(enablepersist==true && ddtreemenu.getCookie(treeid)!="")? ddtreemenu.getCookie(treeid).split(",") : "" -for (var i=0; iset_body('

    '.$logger_overview[$lang].'

    '); - -if ($_GET[a]) { - - $offset_start=$_GET[a]; - - if (!ctype_digit($offset_start)) { - - unset($offset_start); - - } - - } - -if (isset($_POST['e']) AND isset($_POST['l'])) { - - $event_id=$_POST['e']; - $level_id=$_POST['l']; - - } - else{ - - $event_id=$_GET['e']; - $level_id=$_GET['l']; - - } - -if (!ctype_digit($event_id) AND !ctype_digit($level_id)) { - - unset($level_id); - unset($event_id); - -} - -$html->set_body('
    -
    -   - - -
    -
    -
    - - - - - - - - '); - -if (!$offset_start) { - - $offset_start="0"; - - } - -if ($event_id === "none") { - - $event_id = null; - - } -if ($level_id === "none") { - - $level_id = null; - - } - -$db->get_num_events($event_id,$level_id); -$nume = $db->result->cnt; - -if ($offset_start>$nume) { - - $offset_start="0"; - - } - -$db->logger_get_events($event_id,$level_id, $offset_start,$lang); -$result = $db->result; - -foreach ($result as $results) { - - if ($results[id_event]=="1" OR $results[id_event]=="3") { - - $ip_desc=$logger_f_ip[$lang]; - - } - else { - - $ip_desc=""; - - } - if ($results[id_level] == "3") { - - $col="main_row_b"; - $f_color="style=\"color: red;\""; - - } - else { - - $col="main_row_a"; - $f_color=""; - - } - $html->set_body(' - - - - '); - -} - -$html->set_body(''); - -// pagination -$html->set_body('
    '.$logger_f1[$lang].''.$logger_f2[$lang].''.$logger_f3[$lang].''.$logger_f4[$lang].'
    '.$results[event].''.$results[log_time].''.$results[level].''.htmlspecialchars($ip_desc.$results[extra]).'
    '); - -for($i=0;$i < $nume;$i=$i+300){ - - if ($i!=$offset_start) { - - if (isset($event_id)){ - - $e="&e=$event_id"; - } - if (isset($level_id)){ - - $l="&l=$level_id"; - } - - $html->set_body(' ['.$i.'] '); - - } - - else { - - $html->set_body(' -'.$i.'- '); - } - -} - -$html->set_body('
    '); -require_once("footer.php"); -?> diff --git a/jorge/main.php b/jorge/main.php deleted file mode 100644 index ccbc1b2..0000000 --- a/jorge/main.php +++ /dev/null @@ -1,536 +0,0 @@ -set_overview('

    '.$archives_t[$lang].'

    '.$cal_notice[$lang].'. '.$change_view_cal[$lang].''); - -if ($enc->decrypt_url($e_string) === true) { - - $tslice = $enc->tslice; - $talker = $enc->peer_name_id; - $server = $enc->peer_server_id; - $action = $enc->action; - $lnk = $enc->lnk; - $e_string = $enc->crypt_url("tslice=$tslice&peer_name_id=$talker&peer_server_id=$server"); - } - else{ - - unset($e_string); - -} - -$html->set_body(' - - - '); - -// undo delete -if ($action === "undelete") { - - if ($db->move_chat_from_trash($talker,$server,$tslice,$lnk) === true) { - - $html->status_message($undo_info[$lang],"message"); - - } - - else { - - unset($talker); - $html->alert_message($oper_fail[$lang],"message"); - - } - -} - -// set idx -if ($_GET['idx']) { - - $idx = $_GET['idx']; - - if ($enc->decrypt_url($idx) === true) { - - if($db->set_ext_index($enc->single) !== true) { - - echo $enc->single;exit; - unset($idx); - unset($action); - - } - - $idx = $enc->single; - - } - else{ - - unset($idx); - unset($action); - - } - -} - -if ($action === "delete") { - - if ($db->move_chat_to_trash($talker,$server,$tslice,$lnk) === true) { - - $undo = $enc->crypt_url("tslice=$tslice&peer_name_id=$talker&peer_server_id=$server&lnk=$lnk&action=undelete"); - unset($talker); - $idx = $enc->crypt_url("single=".$db->get_last_idx().""); - $html->set_body('
    '.$del_moved[$lang] - .' Undo
    '); - - } - - else { - - $html->alert_message($oper_fail[$lang],"message"); - unset($talker); - - } - -} - -// some validation things... -if ($start) { - - if ((validate_start($start))!==true) { - - $start="0"; - - } - -} - -$db->get_user_stats_drop_down(); -$result = $db->result; - -if (count($result) !=0) { - - // main table - $html->set_body('

    - - '); - if ($tslice) { - - $html->set_body(''); - } - if ($talker) { - - $html->set_body(''); - - } - - $html->set_body(''); - - } -} - -// Chat thread: -if ($talker) { - - $html->set_body('
    '.$main_date[$lang].''.$talks[$lang].''.$thread[$lang].'
      '); - - foreach ($result as $entry) { - - if ($entry[at_send]==substr($tslice,0,7)) { - - $rel="open"; $bop=""; $bcl=""; - - } - else { - - $rel=""; - $bop=""; - $bcl=""; - - } - - $html->set_body('
    • '.$bop.verbose_date($entry[at],$months_names,$weekdays,false,true).$bcl.'
        '); - $db->get_folder_content($entry[at_send]); - $result2 = $db->result; - foreach($result2 as $ent) { - - $to_base = $enc->crypt_url("tslice=$ent[at]"); - if ($tslice==$ent["at"]) { - - $bold_b = ""; - $bold_e=""; - } - else { - - $bold_b=""; - $bold_e=""; - - } - - $html->set_body('
      • '.$bold_b.verbose_date($ent["at"],$months_names,$weekdays,true).$bold_e.'
      • '); - - } - - $html->set_body('
    • '); - - } - - $html->set_body(' - -
    - - - - '); - - $html->set_body('
    '); - - } - else { - - $html->status_message($no_archives[$lang]); -} - -// Chats in selected days: -if ($tslice) { - - $db->get_user_chats($tslice); - $result = $db->result; - if (count($result)>0) { - - $display_conversations = true; - - } - else{ - - $display_conversations = false; - - } - -if ($display_conversations === true) { - - // we need to sort list by nickname so we need to combiet 2 results: roster and mod_logdb chatlist: - foreach($result as $sort_me) { - - $roster_name = query_nick_name($ejabberd_roster,$sort_me[username],$sort_me[server_name]); - $arr_key++; - if (!$roster_name) { - - // split contact into 2 arrays: one with full jids, second without names - transports, agents.. - $sorted_spec[$arr_key] = array( - "roster_name"=>$roster_name, - "username"=>$sort_me[username], - "server_name"=>$sort_me[server_name], - "todaytalk"=>$sort_me[todaytalk], - "server"=>$sort_me[server], - "lcount"=>$sort_me[lcount] - ); - } - else { - - $sorted_list[$arr_key] = array( - "roster_name"=>$roster_name, - "username"=>$sort_me[username], - "server_name"=>$sort_me[server_name], - "todaytalk"=>$sort_me[todaytalk], - "server"=>$sort_me[server], - "lcount"=>$sort_me[lcount] - ); - } - - } - - // sort list - asort($sorted_list); - - if (!$show_spec) { - - $show_spec="1"; - - } - - if ($sorted_spec AND $show_spec === "1") { - - if ($sorted_list) { - - $sorted_list = array_merge($sorted_list,$sorted_spec); - - } - else{ - - $sorted_list = $sorted_spec; - - } - - } - - $html->set_body('
    - '); - foreach ($sorted_list as $entry) { - - $user_name = $entry[username]; - $server_name = $entry[server_name]; - if ($talker == $entry["todaytalk"] AND $server==$entry[server]) { - - $bold_b=""; $bold_e=""; - - } - else { - - $bold_b=""; - $bold_e=""; - - } - - $nickname = $entry[roster_name]; - if (!$nickname) { - - $nickname=$not_in_r[$lang]; - unset($malpa); - $calday_class="caldays4"; - $spec_con = '
    ('.htmlspecialchars($server_name).')'; - - } - else{ - - $malpa = "@"; - unset($spec_con); - unset($calday_class); - - } - - $to_base2 = $enc->crypt_url("tslice=$tslice&peer_name_id=$entry[todaytalk]&peer_server_id=$entry[server]"); - $html->set_body(' - '); - } - - $html->set_body('
    - '.$bold_b.cut_nick($nickname).$bold_e.''); - if ($spec_con) { - - $html->set_body($bold_b.$spec_con.$bold_e); - } - - $html->set_body('
    '); - if (!$start) { - - $start="0"; - } - $db->get_num_lines($tslice,$talker,$server); - $nume = $db->result->cnt; - if ($start>$nume) { - - $start=$nume-$num_lines_bro; - - } - - $db->get_user_name($talker); - $talker_name = $db->result->username; - $db->get_server_name($server); - $server_name = $db->result->server_name; - $nickname = query_nick_name($ejabberd_roster,$talker_name,$server_name); - if ($nickname === "") { - - $nickname=$not_in_r[$lang]; - $spec_mark = true; - } - else { - - $spec_mark = false; - - } - $predefined = $enc->crypt_url("jid=$talker_name@$server_name"); - $html->set_body('
    '); - if ($_GET['loc']) { - - $loc_id=$_GET['loc']; - if ($loc_id=="2") { - - $back_link_message=$chat_map_back[$lang]; - $back_link="chat_map.php?chat_map=$predefined"; - - } - elseif($loc_id=="3") { - - $back_link_message=$fav_back[$lang]; - $back_link="favorites.php"; - - } - elseif($loc_id=="4") { - - $back_link_message=$myl_back[$lang]; - $back_link="my_links.php"; - } - - $html->set_body(''); - } - if ($resource_id) { - - $db->get_resource_name($resource_id); - $res_display = $db->result->resource_name; - $html->set_body(''); - - } - - $action_link = $enc->crypt_url("tslice=$tslice&peer_name_id=$talker&peer_server_id=$server&lnk=$e_string&action=delete"); - - $html->set_body(' - - - - - '); - - if($db->get_user_chat($tslice,$talker,$server,$resource_id,$start,$num_lines_bro) === false) { - - $html->alert_message($oper_fail[$lang]); - - } - // processing messages. this should be handled as separate message_processor, so that tree view and calendar view can share the same code withoud redundancy. To be done in 2.0 - $result = $db->result; - - // some strings to pass to message_processor - $lang_pack = array( - $cont_chat_p[$lang], - $message_type_message[$lang], - $message_type_error[$lang], - $message_type_headline[$lang], - $resource_only[$lang], - $muc_message[$lang], - $my_links_save[$lang], - $verb_h[$lang], - $in_min[$lang] - ); - - // Sent all data to parsing function (message processor) - if (message_processor($tslice,$server_name,$start,$nickname,$result,$db,$html,$enc,TOKEN,$split_line,$lang_pack,$lang,$spec_mark,$e_string) !== true) { - - $html->alert_message($oper_fail[$lang]); - $html->destroy_content(); - - } - - $html->set_body(''); - // limiting code - end - - if (($nume-$start)>40) { - - $html->set_body(''); - - } - - $html->set_body('
    '.$back_link_message.'
    '.$resource_warn[$lang].cut_nick(htmlspecialchars($res_display)).'. '); - $html->set_body($resource_discard[$lang].''.$resource_discard2[$lang].'
    '.$time_t[$lang].' '.$user_t[$lang].' '.$thread[$lang].' - '); - - // check favorite - $db->check_favorite($talker,$server,$tslice); - if ($db->result->cnt < 1) { - - $html->set_body(' -
    - - - -
    - '); - } - else { - - $html->set_body(' -
    - - - '.$fav_favorited[$lang].' -
    - '); - - - } - - $html->set_body(' - '.$export_link[$lang].'  |   - '.$all_for_u[$lang].' - '.$all_for_u_m2[$lang].' -  |  - '.$all_for_u_m[$lang].' -   |   - '.$del_t[$lang].'
    '); - - for($i=0;$i < $nume;$i=$i+$num_lines_bro){ - - if ($i!=$start) { - - if ($resource_id) { - - $add_res="&b=$resource_id"; - - } - else { - - $add_res=""; - - } - - $html->set_body(' ['.$i.'] '); - - } - else { - - $html->set_body(' -'.$i.'- '); - } - - } - - $html->set_body('
    '.$back_t[$lang].'
    '); -} - -$html->set_body(''); - -require_once("footer.php"); -?> diff --git a/jorge/mod_logdb/erlang-mysql_userflag.diff b/jorge/mod_logdb/erlang-mysql_userflag.diff deleted file mode 100644 index eb54246..0000000 --- a/jorge/mod_logdb/erlang-mysql_userflag.diff +++ /dev/null @@ -1,180 +0,0 @@ -Index: mysql_conn.erl -=================================================================== ---- mysql_conn.erl (revision 861) -+++ mysql_conn.erl (working copy) -@@ -64,6 +64,7 @@ - %% External exports - %%-------------------------------------------------------------------- - -export([start/6, -+ start/7, - start_link/6, - fetch/3, - fetch/4, -@@ -99,12 +100,14 @@ - - %%-------------------------------------------------------------------- - %% Function: start(Host, Port, User, Password, Database, LogFun) -+%% Function: start(Host, Port, User, Password, Database, UserFlags, LogFun) - %% Function: start_link(Host, Port, User, Password, Database, LogFun) - %% Host = string() - %% Port = integer() - %% User = string() - %% Password = string() - %% Database = string() -+%% UserFlags = list() - %% LogFun = undefined | function() of arity 3 - %% Descrip.: Starts a mysql_conn process that connects to a MySQL - %% server, logs in and chooses a database. -@@ -112,11 +115,13 @@ - %% Pid = pid() - %% Reason = string() - %%-------------------------------------------------------------------- --start(Host, Port, User, Password, Database, LogFun) when is_list(Host), is_integer(Port), is_list(User), -- is_list(Password), is_list(Database) -> -+start(Host, Port, User, Password, Database, LogFun) -> -+ start(Host, Port, User, Password, Database, [], LogFun). -+start(Host, Port, User, Password, Database, UserFlags, LogFun) when is_list(Host), is_integer(Port), is_list(User), -+ is_list(Password), is_list(Database), is_list(UserFlags) -> - ConnPid = self(), - Pid = spawn(fun () -> -- init(Host, Port, User, Password, Database, LogFun, ConnPid) -+ init(Host, Port, User, Password, Database, UserFlags, LogFun, ConnPid) - end), - post_start(Pid, LogFun). - -@@ -124,7 +129,7 @@ - is_list(Password), is_list(Database) -> - ConnPid = self(), - Pid = spawn_link(fun () -> -- init(Host, Port, User, Password, Database, LogFun, ConnPid) -+ init(Host, Port, User, Password, Database, [], LogFun, ConnPid) - end), - post_start(Pid, LogFun). - -@@ -243,6 +248,7 @@ - %% User = string() - %% Password = string() - %% Database = string() -+%% UserFlags = list() - %% LogFun = undefined | function() of arity 3 - %% Parent = pid() of process starting this mysql_conn - %% Descrip.: Connect to a MySQL server, log in and chooses a database. -@@ -250,10 +256,10 @@ - %% we were successfull. - %% Returns : void() | does not return - %%-------------------------------------------------------------------- --init(Host, Port, User, Password, Database, LogFun, Parent) -> -+init(Host, Port, User, Password, Database, UserFlags, LogFun, Parent) -> - case mysql_recv:start_link(Host, Port, LogFun, self()) of - {ok, RecvPid, Sock} -> -- case mysql_init(Sock, RecvPid, User, Password, LogFun) of -+ case mysql_init(Sock, RecvPid, User, Password, UserFlags, LogFun) of - {ok, Version} -> - case do_query(Sock, RecvPid, LogFun, "use " ++ Database, Version, [{result_type, binary}]) of - {error, MySQLRes} -> -@@ -318,7 +324,7 @@ - end. - - %%-------------------------------------------------------------------- --%% Function: mysql_init(Sock, RecvPid, User, Password, LogFun) -+%% Function: mysql_init(Sock, RecvPid, User, Password, UserFlags, LogFun) - %% Sock = term(), gen_tcp socket - %% RecvPid = pid(), mysql_recv process - %% User = string() -@@ -328,16 +334,16 @@ - %% Returns : ok | {error, Reason} - %% Reason = string() - %%-------------------------------------------------------------------- --mysql_init(Sock, RecvPid, User, Password, LogFun) -> -+mysql_init(Sock, RecvPid, User, Password, UserFlags, LogFun) -> - case do_recv(LogFun, RecvPid, undefined) of - {ok, Packet, InitSeqNum} -> - {Version, Salt1, Salt2, Caps} = greeting(Packet, LogFun), - AuthRes = - case Caps band ?SECURE_CONNECTION of - ?SECURE_CONNECTION -> -- mysql_auth:do_new_auth(Sock, RecvPid, InitSeqNum + 1, User, Password, Salt1, Salt2, LogFun); -+ mysql_auth:do_new_auth(Sock, RecvPid, InitSeqNum + 1, User, Password, UserFlags, Salt1, Salt2, LogFun); - _ -> -- mysql_auth:do_old_auth(Sock, RecvPid, InitSeqNum + 1, User, Password, Salt1, LogFun) -+ mysql_auth:do_old_auth(Sock, RecvPid, InitSeqNum + 1, User, Password, UserFlags, Salt1, LogFun) - end, - case AuthRes of - {ok, <<0:8, _Rest/binary>>, _RecvNum} -> -Index: mysql_auth.erl -=================================================================== ---- mysql_auth.erl (revision 861) -+++ mysql_auth.erl (working copy) -@@ -17,8 +17,8 @@ - %% External exports (should only be used by the 'mysql_conn' module) - %%-------------------------------------------------------------------- - -export([ -- do_old_auth/7, -- do_new_auth/8 -+ do_old_auth/8, -+ do_new_auth/9 - ]). - - %%-------------------------------------------------------------------- -@@ -51,9 +51,9 @@ - %% Descrip.: Perform old-style MySQL authentication. - %% Returns : result of mysql_conn:do_recv/3 - %%-------------------------------------------------------------------- --do_old_auth(Sock, RecvPid, SeqNum, User, Password, Salt1, LogFun) -> -+do_old_auth(Sock, RecvPid, SeqNum, User, Password, UserFlags, Salt1, LogFun) -> - Auth = password_old(Password, Salt1), -- Packet2 = make_auth(User, Auth), -+ Packet2 = make_auth(User, Auth, UserFlags), - do_send(Sock, Packet2, SeqNum, LogFun), - mysql_conn:do_recv(LogFun, RecvPid, SeqNum). - -@@ -71,9 +71,9 @@ - %% Descrip.: Perform MySQL authentication. - %% Returns : result of mysql_conn:do_recv/3 - %%-------------------------------------------------------------------- --do_new_auth(Sock, RecvPid, SeqNum, User, Password, Salt1, Salt2, LogFun) -> -+do_new_auth(Sock, RecvPid, SeqNum, User, Password, UserFlags, Salt1, Salt2, LogFun) -> - Auth = password_new(Password, Salt1 ++ Salt2), -- Packet2 = make_new_auth(User, Auth, none), -+ Packet2 = make_new_auth(User, Auth, none, UserFlags), - do_send(Sock, Packet2, SeqNum, LogFun), - case mysql_conn:do_recv(LogFun, RecvPid, SeqNum) of - {ok, Packet3, SeqNum2} -> -@@ -105,9 +105,11 @@ - end, L)). - - %% part of do_old_auth/4, which is part of mysql_init/4 --make_auth(User, Password) -> -- Caps = ?LONG_PASSWORD bor ?LONG_FLAG -- bor ?TRANSACTIONS bor ?FOUND_ROWS, -+make_auth(User, Password, UserFlags) -> -+ Flags = lists:append(UserFlags, [?LONG_PASSWORD, ?LONG_FLAG, ?TRANSACTIONS, ?FOUND_ROWS]), -+ Caps = lists:foldl(fun(Flag, TCaps) when is_integer(Flag) -> -+ TCaps bor Flag -+ end, 0, Flags), - Maxsize = 0, - UserB = list_to_binary(User), - PasswordB = Password, -@@ -115,16 +117,18 @@ - PasswordB/binary>>. - - %% part of do_new_auth/4, which is part of mysql_init/4 --make_new_auth(User, Password, Database) -> -+make_new_auth(User, Password, Database, UserFlags) -> - DBCaps = case Database of - none -> - 0; - _ -> - ?CONNECT_WITH_DB - end, -- Caps = ?LONG_PASSWORD bor ?LONG_FLAG bor ?TRANSACTIONS bor -- ?PROTOCOL_41 bor ?SECURE_CONNECTION bor DBCaps -- bor ?FOUND_ROWS, -+ -+ Flags = lists:append(UserFlags, [?LONG_PASSWORD, ?LONG_FLAG, ?TRANSACTIONS, ?PROTOCOL_41, ?SECURE_CONNECTION, DBCaps, ?FOUND_ROWS]), -+ Caps = lists:foldl(fun(Flag, TCaps) when is_integer(Flag) -> -+ TCaps bor Flag -+ end, DBCaps, Flags), - Maxsize = ?MAX_PACKET_SIZE, - UserB = list_to_binary(User), - PasswordL = size(Password), diff --git a/jorge/mod_logdb/patch-src-mod_logdb-2.0.3.diff b/jorge/mod_logdb/patch-src-mod_logdb-2.0.3.diff deleted file mode 100644 index 24ab753..0000000 --- a/jorge/mod_logdb/patch-src-mod_logdb-2.0.3.diff +++ /dev/null @@ -1,6647 +0,0 @@ ---- mod_logdb.erl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ mod_logdb.erl 2009-02-05 19:19:51.000000000 +0200 -@@ -0,0 +1,2094 @@ -+%%%---------------------------------------------------------------------- -+%%% File : mod_logdb.erl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : Frontend for log user messages to db -+%%% Version : trunk -+%%% Id : $Id: mod_logdb.erl 1272 2009-02-05 17:16:20Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-module(mod_logdb). -+-author('o.palij@gmail.com'). -+ -+-behaviour(gen_server). -+-behaviour(gen_mod). -+ -+% supervisor -+-export([start_link/2]). -+% gen_mod -+-export([start/2,stop/1]). -+% gen_server -+-export([code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2]). -+% hooks -+-export([send_packet/3, receive_packet/4, offline_packet/3, remove_user/2]). -+-export([get_local_identity/5, -+ get_local_features/5, -+ get_local_items/5, -+ adhoc_local_items/4, -+ adhoc_local_commands/4 -+% get_sm_identity/5, -+% get_sm_features/5, -+% get_sm_items/5, -+% adhoc_sm_items/4, -+% adhoc_sm_commands/4]). -+ ]). -+% ejabberdctl -+-export([rebuild_stats/3, -+ copy_messages/1, copy_messages_ctl/3, copy_messages_int_tc/1]). -+% -+-export([get_vhost_stats/1, get_vhost_stats_at/2, -+ get_user_stats/2, get_user_messages_at/3, -+ get_dates/1, -+ sort_stats/1, -+ convert_timestamp/1, convert_timestamp_brief/1, -+ get_user_settings/2, set_user_settings/3, -+ user_messages_at_parse_query/4, user_messages_parse_query/3, -+ vhost_messages_parse_query/2, vhost_messages_at_parse_query/4, -+ list_to_bool/1, bool_to_list/1, -+ list_to_string/1, string_to_list/1, -+ get_module_settings/1, set_module_settings/2, -+ purge_old_records/2]). -+% webadmin hooks -+-export([webadmin_menu/3, -+ webadmin_user/4, -+ webadmin_page/3, -+ user_parse_query/5]). -+% webadmin queries -+-export([vhost_messages_stats/3, -+ vhost_messages_stats_at/4, -+ user_messages_stats/4, -+ user_messages_stats_at/5]). -+ -+-include("mod_logdb.hrl"). -+-include("ejabberd.hrl"). -+-include("mod_roster.hrl"). -+-include("jlib.hrl"). -+-include("ejabberd_ctl.hrl"). -+-include("adhoc.hrl"). -+-include("web/ejabberd_web_admin.hrl"). -+-include("web/ejabberd_http.hrl"). -+ -+-define(PROCNAME, ejabberd_mod_logdb). -+% gen_server call timeout -+-define(CALL_TIMEOUT, 10000). -+ -+-record(state, {vhost, dbmod, backendPid, monref, purgeRef, pollRef, dbopts, dbs, dolog_default, ignore_jids, groupchat, purge_older_days, poll_users_settings, drop_messages_on_user_removal}). -+ -+ets_settings_table(VHost) -> list_to_atom("ets_logdb_settings_" ++ VHost). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_mod/gen_server callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% ejabberd starts module -+start(VHost, Opts) -> -+ ChildSpec = -+ {gen_mod:get_module_proc(VHost, ?PROCNAME), -+ {?MODULE, start_link, [VHost, Opts]}, -+ permanent, -+ 1000, -+ worker, -+ [?MODULE]}, -+ % add child to ejabberd_sup -+ supervisor:start_child(ejabberd_sup, ChildSpec). -+ -+% supervisor starts gen_server -+start_link(VHost, Opts) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ {ok, Pid} = gen_server:start_link({local, Proc}, ?MODULE, [VHost, Opts], []), -+ Pid ! start, -+ {ok, Pid}. -+ -+init([VHost, Opts]) -> -+ process_flag(trap_exit, true), -+ DBs = gen_mod:get_opt(dbs, Opts, [{mnesia, []}]), -+ VHostDB = gen_mod:get_opt(vhosts, Opts, [{VHost, mnesia}]), -+ % 10 is default becouse of using in clustered environment -+ PollUsersSettings = gen_mod:get_opt(poll_users_settings, Opts, 10), -+ -+ {value,{_, DBName}} = lists:keysearch(VHost, 1, VHostDB), -+ {value, {DBName, DBOpts}} = lists:keysearch(DBName, 1, DBs), -+ -+ ?MYDEBUG("Starting mod_logdb for ~p with ~p backend", [VHost, DBName]), -+ -+ DBMod = list_to_atom(atom_to_list(?MODULE) ++ "_" ++ atom_to_list(DBName)), -+ -+ {ok, #state{vhost=VHost, -+ dbmod=DBMod, -+ dbopts=DBOpts, -+ % dbs used for convert messages from one backend to other -+ dbs=DBs, -+ dolog_default=gen_mod:get_opt(dolog_default, Opts, true), -+ drop_messages_on_user_removal=gen_mod:get_opt(drop_messages_on_user_removal, Opts, true), -+ ignore_jids=gen_mod:get_opt(ignore_jids, Opts, []), -+ groupchat=gen_mod:get_opt(groupchat, Opts, none), -+ purge_older_days=gen_mod:get_opt(purge_older_days, Opts, never), -+ poll_users_settings=PollUsersSettings}}. -+ -+cleanup(#state{vhost=VHost} = State) -> -+ ?MYDEBUG("Stopping ~s for ~p", [?MODULE, VHost]), -+ -+ %ets:delete(ets_settings_table(VHost)), -+ -+ ejabberd_hooks:delete(remove_user, VHost, ?MODULE, remove_user, 90), -+ ejabberd_hooks:delete(user_send_packet, VHost, ?MODULE, send_packet, 90), -+ ejabberd_hooks:delete(user_receive_packet, VHost, ?MODULE, receive_packet, 90), -+ ejabberd_hooks:delete(offline_message_hook, VHost, ?MODULE, offline_packet, 10), -+ %ejabberd_hooks:delete(adhoc_sm_commands, VHost, ?MODULE, adhoc_sm_commands, 110), -+ %ejabberd_hooks:delete(adhoc_sm_items, VHost, ?MODULE, adhoc_sm_items, 110), -+ ejabberd_hooks:delete(adhoc_local_commands, VHost, ?MODULE, adhoc_local_commands, 110), -+ ejabberd_hooks:delete(adhoc_local_items, VHost, ?MODULE, adhoc_local_items, 110), -+ %ejabberd_hooks:delete(disco_sm_identity, VHost, ?MODULE, get_sm_identity, 110), -+ %ejabberd_hooks:delete(disco_sm_features, VHost, ?MODULE, get_sm_features, 110), -+ %ejabberd_hooks:delete(disco_sm_items, VHost, ?MODULE, get_sm_items, 110), -+ ejabberd_hooks:delete(disco_local_identity, VHost, ?MODULE, get_local_identity, 110), -+ ejabberd_hooks:delete(disco_local_features, VHost, ?MODULE, get_local_features, 110), -+ ejabberd_hooks:delete(disco_local_items, VHost, ?MODULE, get_local_items, 110), -+ -+ ejabberd_hooks:delete(webadmin_menu_host, VHost, ?MODULE, webadmin_menu, 70), -+ ejabberd_hooks:delete(webadmin_user, VHost, ?MODULE, webadmin_user, 50), -+ ejabberd_hooks:delete(webadmin_page_host, VHost, ?MODULE, webadmin_page, 50), -+ ejabberd_hooks:delete(webadmin_user_parse_query, VHost, ?MODULE, user_parse_query, 50), -+ -+ ?MYDEBUG("Removed hooks for ~p", [VHost]), -+ -+ ejabberd_ctl:unregister_commands(VHost, [{"rebuild_stats", "rebuild mod_logdb module stats for vhost"}], ?MODULE, rebuild_stats), -+ Supported_backends = lists:flatmap(fun({Backend, _Opts}) -> -+ [atom_to_list(Backend), " "] -+ end, State#state.dbs), -+ ejabberd_ctl:unregister_commands( -+ VHost, -+ [{"copy_messages backend", "copy messages from backend to current backend. backends could be: " ++ Supported_backends }], -+ ?MODULE, copy_messages_ctl), -+ ?MYDEBUG("Unregistered commands for ~p", [VHost]). -+ -+stop(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ %gen_server:call(Proc, {cleanup}), -+ %?MYDEBUG("Cleanup in stop finished!!!!", []), -+ %timer:sleep(10000), -+ ok = supervisor:terminate_child(ejabberd_sup, Proc), -+ ok = supervisor:delete_child(ejabberd_sup, Proc). -+ -+handle_call({cleanup}, _From, State) -> -+ cleanup(State), -+ ?MYDEBUG("Cleanup finished!!!!!", []), -+ {reply, ok, State}; -+handle_call({get_dates}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:get_dates(VHost), -+ {reply, Reply, State}; -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% ejabberd_web_admin callbacks -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+handle_call({delete_messages_by_user_at, PMsgs, Date}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:delete_messages_by_user_at(VHost, PMsgs, Date), -+ {reply, Reply, State}; -+handle_call({delete_all_messages_by_user_at, User, Date}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:delete_all_messages_by_user_at(User, VHost, Date), -+ {reply, Reply, State}; -+handle_call({delete_messages_at, Date}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:delete_messages_at(VHost, Date), -+ {reply, Reply, State}; -+handle_call({get_vhost_stats}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:get_vhost_stats(VHost), -+ {reply, Reply, State}; -+handle_call({get_vhost_stats_at, Date}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:get_vhost_stats_at(VHost, Date), -+ {reply, Reply, State}; -+handle_call({get_user_stats, User}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:get_user_stats(User, VHost), -+ {reply, Reply, State}; -+handle_call({get_user_messages_at, User, Date}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Reply = DBMod:get_user_messages_at(User, VHost, Date), -+ {reply, Reply, State}; -+handle_call({get_user_settings, User}, _From, #state{dbmod=_DBMod, vhost=VHost}=State) -> -+ Reply = case ets:match_object(ets_settings_table(VHost), -+ #user_settings{owner_name=User, _='_'}) of -+ [Set] -> Set; -+ _ -> #user_settings{owner_name=User, -+ dolog_default=State#state.dolog_default, -+ dolog_list=[], -+ donotlog_list=[]} -+ end, -+ {reply, Reply, State}; -+% TODO: remove User ?? -+handle_call({set_user_settings, User, GSet}, _From, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ Set = GSet#user_settings{owner_name=User}, -+ Reply = -+ case ets:match_object(ets_settings_table(VHost), -+ #user_settings{owner_name=User, _='_'}) of -+ [Set] -> -+ ?MYDEBUG("Settings is equal", []), -+ ok; -+ _ -> -+ case DBMod:set_user_settings(User, VHost, Set) of -+ error -> -+ error; -+ ok -> -+ true = ets:insert(ets_settings_table(VHost), Set), -+ ok -+ end -+ end, -+ {reply, Reply, State}; -+handle_call({get_module_settings}, _From, State) -> -+ {reply, State, State}; -+handle_call({set_module_settings, #state{purge_older_days=PurgeDays, -+ poll_users_settings=PollSec} = Settings}, -+ _From, -+ #state{purgeRef=PurgeRefOld, -+ pollRef=PollRefOld, -+ purge_older_days=PurgeDaysOld, -+ poll_users_settings=PollSecOld} = State) -> -+ PurgeRef = if -+ PurgeDays == never, PurgeDaysOld /= never -> -+ {ok, cancel} = timer:cancel(PurgeRefOld), -+ disabled; -+ is_integer(PurgeDays), PurgeDaysOld == never -> -+ set_purge_timer(PurgeDays); -+ true -> -+ PurgeRefOld -+ end, -+ -+ PollRef = if -+ PollSec == PollSecOld -> -+ PollRefOld; -+ PollSec == 0, PollSecOld /= 0 -> -+ {ok, cancel} = timer:cancel(PollRefOld), -+ disabled; -+ is_integer(PollSec), PollSecOld == 0 -> -+ set_poll_timer(PollSec); -+ is_integer(PollSec), PollSecOld /= 0 -> -+ {ok, cancel} = timer:cancel(PollRefOld), -+ set_poll_timer(PollSec) -+ end, -+ -+ NewState = State#state{dolog_default=Settings#state.dolog_default, -+ ignore_jids=Settings#state.ignore_jids, -+ groupchat=Settings#state.groupchat, -+ drop_messages_on_user_removal=Settings#state.drop_messages_on_user_removal, -+ purge_older_days=PurgeDays, -+ poll_users_settings=PollSec, -+ purgeRef=PurgeRef, -+ pollRef=PollRef}, -+ {reply, ok, NewState}; -+handle_call(Msg, _From, State) -> -+ ?INFO_MSG("Got call Msg: ~p, State: ~p", [Msg, State]), -+ {noreply, State}. -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% end ejabberd_web_admin callbacks -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+ -+% ejabberd_hooks call -+handle_cast({addlog, Direction, Owner, Peer, Packet}, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ case filter(Owner, Peer, State) of -+ true -> -+ case catch packet_parse(Owner, Peer, Packet, Direction, State) of -+ ignore -> -+ ok; -+ {'EXIT', Reason} -> -+ ?ERROR_MSG("Failed to parse: ~p", [Reason]); -+ Msg -> -+ DBMod:log_message(VHost, Msg) -+ end; -+ false -> -+ ok -+ end, -+ {noreply, State}; -+handle_cast({remove_user, User}, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ case State#state.drop_messages_on_user_removal of -+ true -> -+ DBMod:drop_user(User, VHost), -+ ?INFO_MSG("Launched ~s@~s removal", [User, VHost]); -+ false -> -+ ?INFO_MSG("Message removing is disabled. Keeping messages for ~s@~s", [User, VHost]) -+ end, -+ {noreply, State}; -+% ejabberdctl rebuild_stats/3 -+handle_cast({rebuild_stats}, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ DBMod:rebuild_stats(VHost), -+ {noreply, State}; -+handle_cast({copy_messages, Backend}, State) -> -+ spawn(?MODULE, copy_messages, [[State, Backend]]), -+ {noreply, State}; -+handle_cast({copy_messages, Backend, Date}, State) -> -+ spawn(?MODULE, copy_messages, [[State, Backend, Date]]), -+ {noreply, State}; -+handle_cast(Msg, State) -> -+ ?INFO_MSG("Got cast Msg:~p, State:~p", [Msg, State]), -+ {noreply, State}. -+ -+% return: disabled | timer reference -+set_purge_timer(PurgeDays) -> -+ case PurgeDays of -+ never -> disabled; -+ Days when is_integer(Days) -> -+ {ok, Ref1} = timer:send_interval(timer:hours(24), scheduled_purging), -+ Ref1 -+ end. -+ -+% return: disabled | timer reference -+set_poll_timer(PollSec) -> -+ if -+ PollSec > 0 -> -+ {ok, Ref2} = timer:send_interval(timer:seconds(PollSec), poll_users_settings), -+ Ref2; -+ % db polling disabled -+ PollSec == 0 -> -+ disabled; -+ true -> -+ {ok, Ref3} = timer:send_interval(timer:seconds(10), poll_users_settings), -+ Ref3 -+ end. -+ -+% actual starting of logging -+% from timer:send_after (in init) -+handle_info(start, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ case DBMod:start(VHost, State#state.dbopts) of -+ {error,{already_started,_}} -> -+ ?MYDEBUG("backend module already started - trying to stop it", []), -+ DBMod:stop(VHost), -+ {stop, already_started, State}; -+ {error, Reason} -> -+ timer:sleep(30000), -+ ?ERROR_MSG("Failed to start: ~p", [Reason]), -+ {stop, db_connection_failed, State}; -+ {ok, SPid} -> -+ ?INFO_MSG("~p connection established", [DBMod]), -+ -+ MonRef = erlang:monitor(process, SPid), -+ -+ ets:new(ets_settings_table(VHost), [named_table,public,set,{keypos, #user_settings.owner_name}]), -+ {ok, DoLog} = DBMod:get_users_settings(VHost), -+ ets:insert(ets_settings_table(VHost), DoLog), -+ -+ TrefPurge = set_purge_timer(State#state.purge_older_days), -+ TrefPoll = set_poll_timer(State#state.poll_users_settings), -+ -+ ejabberd_hooks:add(remove_user, VHost, ?MODULE, remove_user, 90), -+ ejabberd_hooks:add(user_send_packet, VHost, ?MODULE, send_packet, 90), -+ ejabberd_hooks:add(user_receive_packet, VHost, ?MODULE, receive_packet, 90), -+ ejabberd_hooks:add(offline_message_hook, VHost, ?MODULE, offline_packet, 10), -+ -+ ejabberd_hooks:add(disco_local_items, VHost, ?MODULE, get_local_items, 110), -+ ejabberd_hooks:add(disco_local_features, VHost, ?MODULE, get_local_features, 110), -+ ejabberd_hooks:add(disco_local_identity, VHost, ?MODULE, get_local_identity, 110), -+ %ejabberd_hooks:add(disco_sm_items, VHost, ?MODULE, get_sm_items, 110), -+ %ejabberd_hooks:add(disco_sm_features, VHost, ?MODULE, get_sm_features, 110), -+ %ejabberd_hooks:add(disco_sm_identity, VHost, ?MODULE, get_sm_identity, 110), -+ ejabberd_hooks:add(adhoc_local_items, VHost, ?MODULE, adhoc_local_items, 110), -+ ejabberd_hooks:add(adhoc_local_commands, VHost, ?MODULE, adhoc_local_commands, 110), -+ %ejabberd_hooks:add(adhoc_sm_items, VHost, ?MODULE, adhoc_sm_items, 110), -+ %ejabberd_hooks:add(adhoc_sm_commands, VHost, ?MODULE, adhoc_sm_commands, 110), -+ -+ ejabberd_hooks:add(webadmin_menu_host, VHost, ?MODULE, webadmin_menu, 70), -+ ejabberd_hooks:add(webadmin_user, VHost, ?MODULE, webadmin_user, 50), -+ ejabberd_hooks:add(webadmin_page_host, VHost, ?MODULE, webadmin_page, 50), -+ ejabberd_hooks:add(webadmin_user_parse_query, VHost, ?MODULE, user_parse_query, 50), -+ -+ ?MYDEBUG("Added hooks for ~p", [VHost]), -+ -+ ejabberd_ctl:register_commands( -+ VHost, -+ [{"rebuild_stats", "rebuild mod_logdb module stats for vhost"}], -+ ?MODULE, rebuild_stats), -+ Supported_backends = lists:flatmap(fun({Backend, _Opts}) -> -+ [atom_to_list(Backend), " "] -+ end, State#state.dbs), -+ ejabberd_ctl:register_commands( -+ VHost, -+ [{"copy_messages backend", "copy messages from backend to current backend. backends could be: " ++ Supported_backends }], -+ ?MODULE, copy_messages_ctl), -+ ?MYDEBUG("Registered commands for ~p", [VHost]), -+ -+ NewState=State#state{monref = MonRef, backendPid=SPid, purgeRef=TrefPurge, pollRef=TrefPoll}, -+ {noreply, NewState}; -+ Rez -> -+ ?ERROR_MSG("Rez=~p", [Rez]), -+ timer:sleep(30000), -+ {stop, db_connection_failed, State} -+ end; -+% from timer:send_interval/2 (in start handle_info) -+handle_info(scheduled_purging, #state{vhost=VHost, purge_older_days=Days} = State) -> -+ ?MYDEBUG("Starting scheduled purging of old records for ~p", [VHost]), -+ spawn(?MODULE, purge_old_records, [VHost, integer_to_list(Days)]), -+ {noreply, State}; -+% from timer:send_interval/2 (in start handle_info) -+handle_info(poll_users_settings, #state{dbmod=DBMod, vhost=VHost}=State) -> -+ {ok, DoLog} = DBMod:get_users_settings(VHost), -+ ?MYDEBUG("DoLog=~p", [DoLog]), -+ true = ets:delete_all_objects(ets_settings_table(VHost)), -+ ets:insert(ets_settings_table(VHost), DoLog), -+ {noreply, State}; -+handle_info({'DOWN', _MonitorRef, process, _Pid, _Info}, State) -> -+ {stop, db_connection_dropped, State}; -+handle_info({fetch_result, _, _}, State) -> -+ ?MYDEBUG("Got timed out mysql fetch result", []), -+ {noreply, State}; -+handle_info(Info, State) -> -+ ?INFO_MSG("Got Info:~p, State:~p", [Info, State]), -+ {noreply, State}. -+ -+terminate(db_connection_failed, _State) -> -+ ok; -+terminate(db_connection_dropped, State) -> -+ ?MYDEBUG("Got terminate with db_connection_dropped", []), -+ cleanup(State), -+ ok; -+terminate(Reason, #state{monref=undefined} = State) -> -+ ?MYDEBUG("Got terminate with undefined monref.~nReason: ~p", [Reason]), -+ cleanup(State), -+ ok; -+terminate(Reason, #state{dbmod=DBMod, vhost=VHost, monref=MonRef, backendPid=Pid} = State) -> -+ ?INFO_MSG("Reason: ~p", [Reason]), -+ case erlang:is_process_alive(Pid) of -+ true -> -+ erlang:demonitor(MonRef, [flush]), -+ DBMod:stop(VHost); -+ false -> -+ ok -+ end, -+ cleanup(State), -+ ok. -+ -+code_change(_OldVsn, State, _Extra) -> -+ {ok, State}. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% ejabberd_hooks callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% TODO: change to/from to list as sql stores it as list -+send_packet(Owner, Peer, P) -> -+ VHost = Owner#jid.lserver, -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {addlog, to, Owner, Peer, P}). -+ -+offline_packet(Peer, Owner, P) -> -+ VHost = Owner#jid.lserver, -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {addlog, from, Owner, Peer, P}). -+ -+receive_packet(_JID, Peer, Owner, P) -> -+ VHost = Owner#jid.lserver, -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {addlog, from, Owner, Peer, P}). -+ -+remove_user(User, Server) -> -+ LUser = jlib:nodeprep(User), -+ LServer = jlib:nameprep(Server), -+ Proc = gen_mod:get_module_proc(LServer, ?PROCNAME), -+ gen_server:cast(Proc, {remove_user, LUser}). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% ejabberdctl -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+rebuild_stats(_Val, VHost, ["rebuild_stats"]) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {rebuild_stats}), -+ {stop, ?STATUS_SUCCESS}; -+rebuild_stats(Val, _VHost, _Args) -> -+ Val. -+ -+copy_messages_ctl(_Val, VHost, ["copy_messages", Backend]) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {copy_messages, Backend}), -+ {stop, ?STATUS_SUCCESS}; -+copy_messages_ctl(_Val, VHost, ["copy_messages", Backend, Date]) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {copy_messages, Backend, Date}), -+ {stop, ?STATUS_SUCCESS}; -+copy_messages_ctl(Val, _VHost, _Args) -> -+ Val. -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% misc operations -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+ -+% handle_cast({addlog, E}, _) -+% raw packet -> #msg -+packet_parse(Owner, Peer, Packet, Direction, State) -> -+ case xml:get_subtag(Packet, "body") of -+ false -> -+ ignore; -+ Body_xml -> -+ Message_type = -+ case xml:get_tag_attr_s("type", Packet) of -+ [] -> "normal"; -+ MType -> MType -+ end, -+ -+ case Message_type of -+ "groupchat" when State#state.groupchat == send, Direction == to -> -+ ok; -+ "groupchat" when State#state.groupchat == send, Direction == from -> -+ throw(ignore); -+ "groupchat" when State#state.groupchat == half -> -+ Rooms = ets:match(muc_online_room, '$1'), -+ Ni=lists:foldl(fun([{muc_online_room, {GName, GHost}, Pid}], Names) -> -+ case gen_fsm:sync_send_all_state_event(Pid, {get_jid_nick,Owner}) of -+ [] -> Names; -+ Nick -> -+ lists:append(Names, [jlib:jid_to_string({GName, GHost, Nick})]) -+ end -+ end, [], Rooms), -+ case lists:member(jlib:jid_to_string(Peer), Ni) of -+ true when Direction == from -> -+ throw(ignore); -+ _ -> -+ ok -+ end; -+ "groupchat" when State#state.groupchat == none -> -+ throw(ignore); -+ _ -> -+ ok -+ end, -+ -+ Message_body = xml:get_tag_cdata(Body_xml), -+ Message_subject = -+ case xml:get_subtag(Packet, "subject") of -+ false -> -+ ""; -+ Subject_xml -> -+ xml:get_tag_cdata(Subject_xml) -+ end, -+ -+ OwnerName = stringprep:tolower(Owner#jid.user), -+ PName = stringprep:tolower(Peer#jid.user), -+ PServer = stringprep:tolower(Peer#jid.server), -+ PResource = Peer#jid.resource, -+ -+ #msg{timestamp=get_timestamp(), -+ owner_name=OwnerName, -+ peer_name=PName, -+ peer_server=PServer, -+ peer_resource=PResource, -+ direction=Direction, -+ type=Message_type, -+ subject=Message_subject, -+ body=Message_body} -+ end. -+ -+% called from handle_cast({addlog, _}, _) -> true (log messages) | false (do not log messages) -+filter(Owner, Peer, State) -> -+ OwnerStr = Owner#jid.luser++"@"++Owner#jid.lserver, -+ OwnerServ = "@"++Owner#jid.lserver, -+ PeerStr = Peer#jid.luser++"@"++Peer#jid.lserver, -+ PeerServ = "@"++Peer#jid.lserver, -+ -+ LogTo = case ets:match_object(ets_settings_table(State#state.vhost), -+ #user_settings{owner_name=Owner#jid.luser, _='_'}) of -+ [#user_settings{dolog_default=Default, -+ dolog_list=DLL, -+ donotlog_list=DNLL}] -> -+ A = lists:member(PeerStr, DLL), -+ B = lists:member(PeerStr, DNLL), -+ if -+ A -> true; -+ B -> false; -+ Default == true -> true; -+ Default == false -> false; -+ true -> State#state.dolog_default -+ end; -+ _ -> State#state.dolog_default -+ end, -+ -+ lists:all(fun(O) -> O end, -+ [not lists:member(OwnerStr, State#state.ignore_jids), -+ not lists:member(PeerStr, State#state.ignore_jids), -+ not lists:member(OwnerServ, State#state.ignore_jids), -+ not lists:member(PeerServ, State#state.ignore_jids), -+ LogTo]). -+ -+purge_old_records(VHost, Days) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ -+ Dates = ?MODULE:get_dates(VHost), -+ DateNow = calendar:datetime_to_gregorian_seconds({date(), {0,0,1}}), -+ DateDiff = list_to_integer(Days)*24*60*60, -+ ?MYDEBUG("Purging tables older than ~s days", [Days]), -+ lists:foreach(fun(Date) -> -+ {ok, [Year, Month, Day]} = regexp:split(Date, "[^0-9]+"), -+ DateInSec = calendar:datetime_to_gregorian_seconds({{list_to_integer(Year), list_to_integer(Month), list_to_integer(Day)}, {0,0,1}}), -+ if -+ (DateNow - DateInSec) > DateDiff -> -+ gen_server:call(Proc, {delete_messages_at, Date}); -+ true -> -+ ?MYDEBUG("Skipping messages at ~p", [Date]) -+ end -+ end, Dates). -+ -+% called from get_vhost_stats/2, get_user_stats/3 -+sort_stats(Stats) -> -+ % Stats = [{"2003-4-15",1}, {"2006-8-18",1}, ... ] -+ CFun = fun({TableName, Count}) -> -+ {ok, [Year, Month, Day]} = regexp:split(TableName, "[^0-9]+"), -+ { calendar:datetime_to_gregorian_seconds({{list_to_integer(Year), list_to_integer(Month), list_to_integer(Day)}, {0,0,1}}), Count } -+ end, -+ % convert to [{63364377601,1}, {63360662401,1}, ... ] -+ CStats = lists:map(CFun, Stats), -+ % sort by date -+ SortedStats = lists:reverse(lists:keysort(1, CStats)), -+ % convert to [{"2007-12-9",1}, {"2007-10-27",1}, ... ] sorted list -+ [{mod_logdb:convert_timestamp_brief(TableSec), Count} || {TableSec, Count} <- SortedStats]. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% Date/Time operations -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% return float seconds elapsed from "zero hour" as list -+get_timestamp() -> -+ {MegaSec, Sec, MicroSec} = now(), -+ [List] = io_lib:format("~.5f", [MegaSec*1000000 + Sec + MicroSec/1000000]), -+ List. -+ -+% convert float seconds elapsed from "zero hour" to local time "%Y-%m-%d %H:%M:%S" string -+convert_timestamp(Seconds) when is_list(Seconds) -> -+ case string:to_float(Seconds++".0") of -+ {F,_} when is_float(F) -> convert_timestamp(F); -+ _ -> erlang:error(badarg, [Seconds]) -+ end; -+convert_timestamp(Seconds) when is_float(Seconds) -> -+ GregSec = trunc(Seconds + 719528*86400), -+ UnivDT = calendar:gregorian_seconds_to_datetime(GregSec), -+ {{Year, Month, Day},{Hour, Minute, Sec}} = calendar:universal_time_to_local_time(UnivDT), -+ integer_to_list(Year) ++ "-" ++ integer_to_list(Month) ++ "-" ++ integer_to_list(Day) ++ " " ++ integer_to_list(Hour) ++ ":" ++ integer_to_list(Minute) ++ ":" ++ integer_to_list(Sec). -+ -+% convert float seconds elapsed from "zero hour" to local time "%Y-%m-%d" string -+convert_timestamp_brief(Seconds) when is_list(Seconds) -> -+ convert_timestamp_brief(list_to_float(Seconds)); -+convert_timestamp_brief(Seconds) when is_float(Seconds) -> -+ GregSec = trunc(Seconds + 719528*86400), -+ UnivDT = calendar:gregorian_seconds_to_datetime(GregSec), -+ {{Year, Month, Day},{_Hour, _Minute, _Sec}} = calendar:universal_time_to_local_time(UnivDT), -+ integer_to_list(Year) ++ "-" ++ integer_to_list(Month) ++ "-" ++ integer_to_list(Day); -+convert_timestamp_brief(Seconds) when is_integer(Seconds) -> -+ {{Year, Month, Day},{_Hour, _Minute, _Sec}} = calendar:gregorian_seconds_to_datetime(Seconds), -+ integer_to_list(Year) ++ "-" ++ integer_to_list(Month) ++ "-" ++ integer_to_list(Day). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% DB operations (get) -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+get_vhost_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats}, ?CALL_TIMEOUT). -+ -+get_vhost_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats_at, Date}, ?CALL_TIMEOUT). -+ -+get_user_stats(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_stats, User}, ?CALL_TIMEOUT). -+ -+get_user_messages_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_messages_at, User, Date}, ?CALL_TIMEOUT). -+ -+get_dates(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_dates}, ?CALL_TIMEOUT). -+ -+get_user_settings(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_settings, User}, ?CALL_TIMEOUT). -+ -+set_user_settings(User, VHost, Set) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {set_user_settings, User, Set}). -+ -+get_module_settings(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_module_settings}). -+ -+set_module_settings(VHost, Settings) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {set_module_settings, Settings}). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% Web admin callbacks (delete) -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+user_messages_at_parse_query(VHost, Date, Msgs, Query) -> -+ case lists:keysearch("delete", 1, Query) of -+ {value, _} -> -+ PMsgs = lists:filter( -+ fun(Msg) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(Msg#msg.timestamp))), -+ lists:member({"selected", ID}, Query) -+ end, Msgs), -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_by_user_at, PMsgs, Date}, ?CALL_TIMEOUT); -+ false -> -+ nothing -+ end. -+ -+user_messages_parse_query(User, VHost, Query) -> -+ case lists:keysearch("delete", 1, Query) of -+ {value, _} -> -+ Dates = get_dates(VHost), -+ PDates = lists:filter( -+ fun(Date) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(User++Date))), -+ lists:member({"selected", ID}, Query) -+ end, Dates), -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ Rez = lists:foldl( -+ fun(Date, Acc) -> -+ lists:append(Acc, -+ [gen_server:call(Proc, -+ {delete_all_messages_by_user_at, User, Date}, -+ ?CALL_TIMEOUT)]) -+ end, [], PDates), -+ case lists:member(error, Rez) of -+ true -> -+ error; -+ false -> -+ nothing -+ end; -+ false -> -+ nothing -+ end. -+ -+vhost_messages_parse_query(VHost, Query) -> -+ case lists:keysearch("delete", 1, Query) of -+ {value, _} -> -+ Dates = get_dates(VHost), -+ PDates = lists:filter( -+ fun(Date) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(VHost++Date))), -+ lists:member({"selected", ID}, Query) -+ end, Dates), -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ Rez = lists:foldl(fun(Date, Acc) -> -+ lists:append(Acc, [gen_server:call(Proc, -+ {delete_messages_at, Date}, -+ ?CALL_TIMEOUT)]) -+ end, [], PDates), -+ case lists:member(error, Rez) of -+ true -> -+ error; -+ false -> -+ nothing -+ end; -+ false -> -+ nothing -+ end. -+ -+vhost_messages_at_parse_query(VHost, Date, Stats, Query) -> -+ case lists:keysearch("delete", 1, Query) of -+ {value, _} -> -+ PStats = lists:filter( -+ fun({User, _Count}) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(User++VHost))), -+ lists:member({"selected", ID}, Query) -+ end, Stats), -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ Rez = lists:foldl(fun({User, _Count}, Acc) -> -+ lists:append(Acc, [gen_server:call(Proc, -+ {delete_all_messages_by_user_at, -+ User, Date}, -+ ?CALL_TIMEOUT)]) -+ end, [], PStats), -+ case lists:member(error, Rez) of -+ true -> -+ error; -+ false -> -+ ok -+ end; -+ false -> -+ nothing -+ end. -+ -+copy_messages([#state{vhost=VHost}=State, From]) -> -+ ?INFO_MSG("Going to copy messages from ~p for ~p", [From, VHost]), -+ -+ {FromDBName, FromDBOpts} = -+ case lists:keysearch(list_to_atom(From), 1, State#state.dbs) of -+ {value, {FN, FO}} -> -+ {FN, FO}; -+ false -> -+ ?ERROR_MSG("Failed to find record for ~p in dbs", [From]), -+ throw(error) -+ end, -+ -+ FromDBMod = list_to_atom(atom_to_list(?MODULE) ++ "_" ++ atom_to_list(FromDBName)), -+ -+ {ok, _FromPid} = FromDBMod:start(VHost, FromDBOpts), -+ -+ Dates = FromDBMod:get_dates(VHost), -+ DatesLength = length(Dates), -+ -+ lists:foldl(fun(Date, Acc) -> -+ case copy_messages_int([FromDBMod, State#state.dbmod, VHost, Date]) of -+ ok -> -+ ?INFO_MSG("Copied messages at ~p (~p/~p)", [Date, Acc, DatesLength]); -+ Value -> -+ ?ERROR_MSG("Failed to copy messages at ~p (~p/~p): ~p", [Date, Acc, DatesLength, Value]), -+ FromDBMod:stop(VHost), -+ throw(error) -+ end, -+ Acc + 1 -+ end, 1, Dates), -+ ?INFO_MSG("Copied messages from ~p", [From]), -+ FromDBMod:stop(VHost); -+copy_messages([#state{vhost=VHost}=State, From, Date]) -> -+ {value, {FromDBName, FromDBOpts}} = lists:keysearch(list_to_atom(From), 1, State#state.dbs), -+ FromDBMod = list_to_atom(atom_to_list(?MODULE) ++ "_" ++ atom_to_list(FromDBName)), -+ {ok, _FromPid} = FromDBMod:start(VHost, FromDBOpts), -+ case catch copy_messages_int([FromDBMod, State#state.dbmod, VHost, Date]) of -+ {'exit', Reason} -> -+ ?ERROR_MSG("Failed to copy messages at ~p: ~p", [Date, Reason]); -+ ok -> -+ ?INFO_MSG("Copied messages at ~p", [Date]); -+ Value -> -+ ?ERROR_MSG("Failed to copy messages at ~p: ~p", [Date, Value]) -+ end, -+ FromDBMod:stop(VHost). -+ -+copy_messages_int([FromDBMod, ToDBMod, VHost, Date]) -> -+ ets:new(mod_logdb_temp, [named_table, set, public]), -+ {Time, Value} = timer:tc(?MODULE, copy_messages_int_tc, [[FromDBMod, ToDBMod, VHost, Date]]), -+ ets:delete_all_objects(mod_logdb_temp), -+ ets:delete(mod_logdb_temp), -+ ?INFO_MSG("copy_messages at ~p elapsed ~p sec", [Date, Time/1000000]), -+ Value. -+ -+copy_messages_int_tc([FromDBMod, ToDBMod, VHost, Date]) -> -+ ?INFO_MSG("Going to copy messages from ~p for ~p at ~p", [FromDBMod, VHost, Date]), -+ -+ ok = FromDBMod:rebuild_stats_at(VHost, Date), -+ catch mod_logdb:rebuild_stats_at(VHost, Date), -+ {ok, FromStats} = FromDBMod:get_vhost_stats_at(VHost, Date), -+ ToStats = case mod_logdb:get_vhost_stats_at(VHost, Date) of -+ {ok, Stats} -> Stats; -+ {error, _} -> [] -+ end, -+ -+ FromStatsS = lists:keysort(1, FromStats), -+ ToStatsS = lists:keysort(1, ToStats), -+ -+ StatsLength = length(FromStats), -+ -+ CopyFun = if -+ % destination table is empty -+ FromDBMod /= mod_logdb_mnesia_old, ToStats == [] -> -+ fun({User, _Count}, Acc) -> -+ {ok, Msgs} = FromDBMod:get_user_messages_at(User, VHost, Date), -+ MAcc = -+ lists:foldl(fun(Msg, MFAcc) -> -+ ok = ToDBMod:log_message(VHost, Msg), -+ MFAcc + 1 -+ end, 0, Msgs), -+ NewAcc = Acc + 1, -+ ?INFO_MSG("Copied ~p messages for ~p (~p/~p) at ~p", [MAcc, User, NewAcc, StatsLength, Date]), -+ %timer:sleep(100), -+ NewAcc -+ end; -+ % destination table is not empty -+ FromDBMod /= mod_logdb_mnesia_old, ToStats /= [] -> -+ fun({User, _Count}, Acc) -> -+ {ok, ToMsgs} = ToDBMod:get_user_messages_at(User, VHost, Date), -+ lists:foreach(fun(#msg{timestamp=Tst}) when length(Tst) == 16 -> -+ ets:insert(mod_logdb_temp, {Tst}); -+ % mysql, pgsql removes final zeros after decimal point -+ (#msg{timestamp=Tst}) when length(Tst) < 16 -> -+ {F, _} = string:to_float(Tst++".0"), -+ [T] = io_lib:format("~.5f", [F]), -+ ets:insert(mod_logdb_temp, {T}) -+ end, ToMsgs), -+ {ok, Msgs} = FromDBMod:get_user_messages_at(User, VHost, Date), -+ MAcc = -+ lists:foldl(fun(#msg{timestamp=ToTimestamp} = Msg, MFAcc) -> -+ case ets:member(mod_logdb_temp, ToTimestamp) of -+ false -> -+ ok = ToDBMod:log_message(VHost, Msg), -+ ets:insert(mod_logdb_temp, {ToTimestamp}), -+ MFAcc + 1; -+ true -> -+ MFAcc -+ end -+ end, 0, Msgs), -+ NewAcc = Acc + 1, -+ ets:delete_all_objects(mod_logdb_temp), -+ ?INFO_MSG("Copied ~p messages for ~p (~p/~p) at ~p", [MAcc, User, NewAcc, StatsLength, Date]), -+ %timer:sleep(100), -+ NewAcc -+ end; -+ % copying from mod_logmnesia -+ true -> -+ fun({User, _Count}, Acc) -> -+ ToStats = -+ case ToDBMod:get_user_messages_at(User, VHost, Date) of -+ {ok, []} -> -+ ok; -+ {ok, ToMsgs} -> -+ lists:foreach(fun(#msg{timestamp=Tst}) when length(Tst) == 16 -> -+ ets:insert(mod_logdb_temp, {Tst}); -+ % mysql, pgsql removes final zeros after decimal point -+ (#msg{timestamp=Tst}) when length(Tst) < 15 -> -+ {F, _} = string:to_float(Tst++".0"), -+ [T] = io_lib:format("~.5f", [F]), -+ ets:insert(mod_logdb_temp, {T}) -+ end, ToMsgs); -+ {error, _} -> -+ ok -+ end, -+ {ok, Msgs} = FromDBMod:get_user_messages_at(User, VHost, Date), -+ -+ MAcc = -+ lists:foldl( -+ fun({msg, TU, TS, TR, FU, FS, FR, Type, Subj, Body, Timest}, -+ MFAcc) -> -+ [Timestamp] = if is_float(Timest) == true -> -+ io_lib:format("~.5f", [Timest]); -+ % early versions of mod_logmnesia -+ is_integer(Timest) == true -> -+ io_lib:format("~.5f", [Timest-719528*86400.0]); -+ true -> -+ ?ERROR_MSG("Incorrect timestamp ~p", [Timest]), -+ throw(error) -+ end, -+ case ets:member(mod_logdb_temp, Timestamp) of -+ false -> -+ if -+ % from -+ TS == VHost -> -+ TMsg = #msg{timestamp=Timestamp, -+ owner_name=TU, -+ peer_name=FU, peer_server=FS, peer_resource=FR, -+ direction=from, -+ type=Type, -+ subject=Subj, body=Body}, -+ ok = ToDBMod:log_message(VHost, TMsg); -+ true -> ok -+ end, -+ if -+ % to -+ FS == VHost -> -+ FMsg = #msg{timestamp=Timestamp, -+ owner_name=FU, -+ peer_name=TU, peer_server=TS, peer_resource=TR, -+ direction=to, -+ type=Type, -+ subject=Subj, body=Body}, -+ ok = ToDBMod:log_message(VHost, FMsg); -+ true -> ok -+ end, -+ ets:insert(mod_logdb_temp, {Timestamp}), -+ MFAcc + 1; -+ true -> % not ets:member -+ MFAcc -+ end % case -+ end, 0, Msgs), % foldl -+ NewAcc = Acc + 1, -+ ?INFO_MSG("Copied ~p messages for ~p (~p/~p) at ~p", [MAcc, User, NewAcc, StatsLength, Date]), -+ %timer:sleep(100), -+ NewAcc -+ end % fun -+ end, % if FromDBMod /= mod_logdb_mnesia_old -+ -+ if -+ FromStats == [] -> -+ ?INFO_MSG("No messages were found at ~p", [Date]); -+ FromStatsS == ToStatsS -> -+ ?INFO_MSG("Stats are equal at ~p", [Date]); -+ FromStatsS /= ToStatsS -> -+ lists:foldl(CopyFun, 0, FromStats), -+ ok = ToDBMod:rebuild_stats_at(VHost, Date) -+ %timer:sleep(1000) -+ end, -+ -+ ok. -+ -+list_to_bool(Num) -> -+ case lists:member(Num, ["t", "true", "y", "yes", "1"]) of -+ true -> -+ true; -+ false -> -+ case lists:member(Num, ["f", "false", "n", "no", "0"]) of -+ true -> -+ false; -+ false -> -+ error -+ end -+ end. -+ -+bool_to_list(true) -> -+ "TRUE"; -+bool_to_list(false) -> -+ "FALSE". -+ -+list_to_string([]) -> -+ ""; -+list_to_string(List) when is_list(List) -> -+ Str = lists:flatmap(fun(Elm) -> Elm ++ "\n" end, List), -+ lists:sublist(Str, length(Str)-1). -+ -+string_to_list(null) -> -+ []; -+string_to_list([]) -> -+ []; -+string_to_list(String) -> -+ {ok, List} = regexp:split(String, "\n"), -+ List. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% ad-hoc (copy/pasted from mod_configure.erl) -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+-define(ITEMS_RESULT(Allow, LNode, Fallback), -+ case Allow of -+ deny -> -+ Fallback; -+ allow -> -+ case get_local_items(LServer, LNode, -+ jlib:jid_to_string(To), Lang) of -+ {result, Res} -> -+ {result, Res}; -+ {error, Error} -> -+ {error, Error} -+ end -+ end). -+ -+get_local_items(Acc, From, #jid{lserver = LServer} = To, "", Lang) -> -+ case gen_mod:is_loaded(LServer, mod_adhoc) of -+ false -> -+ Acc; -+ _ -> -+ Items = case Acc of -+ {result, Its} -> Its; -+ empty -> [] -+ end, -+ AllowUser = acl:match_rule(LServer, mod_logdb, From), -+ AllowAdmin = acl:match_rule(LServer, mod_logdb_admin, From), -+ if -+ AllowUser == allow; AllowAdmin == allow -> -+ case get_local_items(LServer, [], -+ jlib:jid_to_string(To), Lang) of -+ {result, Res} -> -+ {result, Items ++ Res}; -+ {error, _Error} -> -+ {result, Items} -+ end; -+ true -> -+ {result, Items} -+ end -+ end; -+get_local_items(Acc, From, #jid{lserver = LServer} = To, Node, Lang) -> -+ case gen_mod:is_loaded(LServer, mod_adhoc) of -+ false -> -+ Acc; -+ _ -> -+ LNode = string:tokens(Node, "/"), -+ AllowAdmin = acl:match_rule(LServer, mod_logdb_admin, From), -+ case LNode of -+ ["mod_logdb"] -> -+ ?ITEMS_RESULT(AllowAdmin, LNode, {error, ?ERR_FORBIDDEN}); -+ ["mod_logdb_users"] -> -+ ?ITEMS_RESULT(AllowAdmin, LNode, {error, ?ERR_FORBIDDEN}); -+ ["mod_logdb_users", [$@ | _]] -> -+ ?ITEMS_RESULT(AllowAdmin, LNode, {error, ?ERR_FORBIDDEN}); -+ ["mod_logdb_users", _User] -> -+ ?ITEMS_RESULT(AllowAdmin, LNode, {error, ?ERR_FORBIDDEN}); -+ ["mod_logdb_settings"] -> -+ ?ITEMS_RESULT(AllowAdmin, LNode, {error, ?ERR_FORBIDDEN}); -+ _ -> -+ Acc -+ end -+ end. -+ -+-define(NODE(Name, Node), -+ {xmlelement, "item", -+ [{"jid", Server}, -+ {"name", translate:translate(Lang, Name)}, -+ {"node", Node}], []}). -+ -+get_local_items(_Host, [], Server, Lang) -> -+ {result, -+ [?NODE("Messages logging engine", "mod_logdb")] -+ }; -+get_local_items(_Host, ["mod_logdb"], Server, Lang) -> -+ {result, -+ [?NODE("Messages logging engine users", "mod_logdb_users"), -+ ?NODE("Messages logging engine settings", "mod_logdb_settings")] -+ }; -+get_local_items(Host, ["mod_logdb_users"], Server, Lang) -> -+ {result, get_all_vh_users(Host, Server, Lang)}; -+get_local_items(_Host, ["mod_logdb_users", [$@ | Diap]], Server, Lang) -> -+ case catch ejabberd_auth:dirty_get_registered_users() of -+ {'EXIT', _Reason} -> -+ ?ERR_INTERNAL_SERVER_ERROR; -+ Users -> -+ SUsers = lists:sort([{S, U} || {U, S} <- Users]), -+ case catch begin -+ {ok, [S1, S2]} = regexp:split(Diap, "-"), -+ N1 = list_to_integer(S1), -+ N2 = list_to_integer(S2), -+ Sub = lists:sublist(SUsers, N1, N2 - N1 + 1), -+ lists:map(fun({S, U}) -> -+ ?NODE(U ++ "@" ++ S, "mod_logdb_users/" ++ U ++ "@" ++ S) -+ end, Sub) -+ end of -+ {'EXIT', _Reason} -> -+ ?ERR_NOT_ACCEPTABLE; -+ Res -> -+ {result, Res} -+ end -+ end; -+get_local_items(_Host, ["mod_logdb_users", _User], _Server, _Lang) -> -+ {result, []}; -+get_local_items(_Host, ["mod_logdb_settings"], _Server, _Lang) -> -+ {result, []}; -+get_local_items(_Host, Item, _Server, _Lang) -> -+ ?MYDEBUG("asked for items in ~p", [Item]), -+ {error, ?ERR_ITEM_NOT_FOUND}. -+ -+-define(INFO_RESULT(Allow, Feats), -+ case Allow of -+ deny -> -+ {error, ?ERR_FORBIDDEN}; -+ allow -> -+ {result, Feats} -+ end). -+ -+get_local_features(Acc, From, #jid{lserver = LServer} = _To, Node, _Lang) -> -+ case gen_mod:is_loaded(LServer, mod_adhoc) of -+ false -> -+ Acc; -+ _ -> -+ LNode = string:tokens(Node, "/"), -+ AllowUser = acl:match_rule(LServer, mod_logdb, From), -+ AllowAdmin = acl:match_rule(LServer, mod_logdb_admin, From), -+ case LNode of -+ ["mod_logdb"] when AllowUser == allow; AllowAdmin == allow -> -+ ?INFO_RESULT(allow, [?NS_COMMANDS]); -+ ["mod_logdb"] -> -+ ?INFO_RESULT(deny, [?NS_COMMANDS]); -+ ["mod_logdb_users"] -> -+ ?INFO_RESULT(AllowAdmin, []); -+ ["mod_logdb_users", [$@ | _]] -> -+ ?INFO_RESULT(AllowAdmin, []); -+ ["mod_logdb_users", _User] -> -+ ?INFO_RESULT(AllowAdmin, [?NS_COMMANDS]); -+ ["mod_logdb_settings"] -> -+ ?INFO_RESULT(AllowAdmin, [?NS_COMMANDS]); -+ [] -> -+ Acc; -+ _ -> -+ %?MYDEBUG("asked for ~p features: ~p", [LNode, Allow]), -+ Acc -+ end -+ end. -+ -+-define(INFO_IDENTITY(Category, Type, Name, Lang), -+ [{xmlelement, "identity", -+ [{"category", Category}, -+ {"type", Type}, -+ {"name", translate:translate(Lang, Name)}], []}]). -+ -+-define(INFO_COMMAND(Name, Lang), -+ ?INFO_IDENTITY("automation", "command-node", Name, Lang)). -+ -+get_local_identity(Acc, _From, _To, Node, Lang) -> -+ LNode = string:tokens(Node, "/"), -+ case LNode of -+ ["mod_logdb"] -> -+ ?INFO_COMMAND("Messages logging engine", Lang); -+ ["mod_logdb_users"] -> -+ ?INFO_COMMAND("Messages logging engine users", Lang); -+ ["mod_logdb_users", [$@ | _]] -> -+ Acc; -+ ["mod_logdb_users", User] -> -+ ?INFO_COMMAND(User, Lang); -+ ["mod_logdb_settings"] -> -+ ?INFO_COMMAND("Messages logging engine settings", Lang); -+ [] -> -+ Acc; -+ _ -> -+ Acc -+ end. -+ -+%get_sm_items(Acc, From, To, Node, Lang) -> -+% ?MYDEBUG("get_sm_items Acc=~p From=~p To=~p Node=~p Lang=~p", [Acc, From, To, Node, Lang]), -+% Acc. -+ -+%get_sm_features(Acc, From, To, Node, Lang) -> -+% ?MYDEBUG("get_sm_features Acc=~p From=~p To=~p Node=~p Lang=~p", [Acc, From, To, Node, Lang]), -+% Acc. -+ -+%get_sm_identity(Acc, From, To, Node, Lang) -> -+% ?MYDEBUG("get_sm_identity Acc=~p From=~p To=~p Node=~p Lang=~p", [Acc, From, To, Node, Lang]), -+% Acc. -+ -+adhoc_local_items(Acc, From, #jid{lserver = LServer, server = Server} = To, -+ Lang) -> -+ Items = case Acc of -+ {result, Its} -> Its; -+ empty -> [] -+ end, -+ Nodes = recursively_get_local_items(LServer, "", Server, Lang), -+ Nodes1 = lists:filter( -+ fun(N) -> -+ Nd = xml:get_tag_attr_s("node", N), -+ F = get_local_features([], From, To, Nd, Lang), -+ case F of -+ {result, [?NS_COMMANDS]} -> -+ true; -+ _ -> -+ false -+ end -+ end, Nodes), -+ {result, Items ++ Nodes1}. -+ -+recursively_get_local_items(_LServer, "mod_logdb_users", _Server, _Lang) -> -+ []; -+recursively_get_local_items(LServer, Node, Server, Lang) -> -+ LNode = string:tokens(Node, "/"), -+ Items = case get_local_items(LServer, LNode, Server, Lang) of -+ {result, Res} -> -+ Res; -+ {error, _Error} -> -+ [] -+ end, -+ Nodes = lists:flatten( -+ lists:map( -+ fun(N) -> -+ S = xml:get_tag_attr_s("jid", N), -+ Nd = xml:get_tag_attr_s("node", N), -+ if (S /= Server) or (Nd == "") -> -+ []; -+ true -> -+ [N, recursively_get_local_items( -+ LServer, Nd, Server, Lang)] -+ end -+ end, Items)), -+ Nodes. -+ -+-define(COMMANDS_RESULT(Allow, From, To, Request), -+ case Allow of -+ deny -> -+ {error, ?ERR_FORBIDDEN}; -+ allow -> -+ adhoc_local_commands(From, To, Request) -+ end). -+ -+adhoc_local_commands(Acc, From, #jid{lserver = LServer} = To, -+ #adhoc_request{node = Node} = Request) -> -+ LNode = string:tokens(Node, "/"), -+ AllowUser = acl:match_rule(LServer, mod_logdb, From), -+ AllowAdmin = acl:match_rule(LServer, mod_logdb_admin, From), -+ case LNode of -+ ["mod_logdb"] when AllowUser == allow; AllowAdmin == allow -> -+ ?COMMANDS_RESULT(allow, From, To, Request); -+ ["mod_logdb_users", _User] when AllowAdmin == allow -> -+ ?COMMANDS_RESULT(allow, From, To, Request); -+ ["mod_logdb_settings"] when AllowAdmin == allow -> -+ ?COMMANDS_RESULT(allow, From, To, Request); -+ _ -> -+ Acc -+ end. -+ -+adhoc_local_commands(From, #jid{lserver = LServer} = _To, -+ #adhoc_request{lang = Lang, -+ node = Node, -+ sessionid = SessionID, -+ action = Action, -+ xdata = XData} = Request) -> -+ LNode = string:tokens(Node, "/"), -+ %% If the "action" attribute is not present, it is -+ %% understood as "execute". If there was no -+ %% element in the first response (which there isn't in our -+ %% case), "execute" and "complete" are equivalent. -+ ActionIsExecute = lists:member(Action, -+ ["", "execute", "complete"]), -+ if Action == "cancel" -> -+ %% User cancels request -+ adhoc:produce_response( -+ Request, -+ #adhoc_response{status = canceled}); -+ XData == false, ActionIsExecute -> -+ %% User requests form -+ case get_form(LServer, LNode, From, Lang) of -+ {result, Form} -> -+ adhoc:produce_response( -+ Request, -+ #adhoc_response{status = executing, -+ elements = Form}); -+ {error, Error} -> -+ {error, Error} -+ end; -+ XData /= false, ActionIsExecute -> -+ %% User returns form. -+ case jlib:parse_xdata_submit(XData) of -+ invalid -> -+ {error, ?ERR_BAD_REQUEST}; -+ Fields -> -+ case set_form(From, LServer, LNode, Lang, Fields) of -+ {result, _Res} -> -+ adhoc:produce_response( -+ #adhoc_response{lang = Lang, -+ node = Node, -+ sessionid = SessionID, -+ status = completed}); -+ {error, Error} -> -+ {error, Error} -+ end -+ end; -+ true -> -+ {error, ?ERR_BAD_REQUEST} -+ end. -+ -+-define(LISTLINE(Label, Value), -+ {xmlelement, "option", [{"label", Label}], -+ [{xmlelement, "value", [], [{xmlcdata, Value}]}]}). -+-define(DEFVAL(Value), {xmlelement, "value", [], [{xmlcdata, Value}]}). -+ -+get_user_form(LUser, LServer, Lang) -> -+ %From = jlib:jid_to_string(jlib:jid_remove_resource(Jid)), -+ #user_settings{dolog_default=DLD, -+ dolog_list=DLL, -+ donotlog_list=DNLL} = get_user_settings(LUser, LServer), -+ {result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}], -+ [{xmlelement, "title", [], -+ [{xmlcdata, -+ translate:translate( -+ Lang, "Messages logging engine settings")}]}, -+ {xmlelement, "instructions", [], -+ [{xmlcdata, -+ translate:translate( -+ Lang, "Set logging preferences")++ ": " ++ LUser ++ "@" ++ LServer}]}, -+ % default to log -+ {xmlelement, "field", [{"type", "list-single"}, -+ {"label", -+ translate:translate(Lang, "Default")}, -+ {"var", "dolog_default"}], -+ [?DEFVAL(atom_to_list(DLD)), -+ ?LISTLINE(translate:translate(Lang, "Log Messages"), "true"), -+ ?LISTLINE(translate:translate(Lang, "Do Not Log Messages"), "false") -+ ]}, -+ % do log list -+ {xmlelement, "field", [{"type", "text-multi"}, -+ {"label", -+ translate:translate( -+ Lang, "Log Messages")}, -+ {"var", "dolog_list"}], -+ [{xmlelement, "value", [], [{xmlcdata, list_to_string(DLL)}]}]}, -+ % do not log list -+ {xmlelement, "field", [{"type", "text-multi"}, -+ {"label", -+ translate:translate( -+ Lang, "Do Not Log Messages")}, -+ {"var", "donotlog_list"}], -+ [{xmlelement, "value", [], [{xmlcdata, list_to_string(DNLL)}]}]} -+ ]}]}. -+ -+get_settings_form(Host, Lang) -> -+ #state{dbmod=DBMod, -+ dbs=DBs, -+ dolog_default=DLD, -+ ignore_jids=IgnoreJids, -+ groupchat=GroupChat, -+ purge_older_days=PurgeDaysT, -+ drop_messages_on_user_removal=MRemoval, -+ poll_users_settings=PollTime} = mod_logdb:get_module_settings(Host), -+ -+ Backends = lists:map(fun({Backend, _Opts}) -> -+ ?LISTLINE(atom_to_list(Backend), atom_to_list(Backend)) -+ end, DBs), -+ DB = lists:sublist(atom_to_list(DBMod), length(atom_to_list(?MODULE)) + 2, length(atom_to_list(DBMod))), -+ DBsL = lists:append([?DEFVAL(DB)], Backends), -+ -+ PurgeDays = -+ case PurgeDaysT of -+ never -> "never"; -+ Num when is_integer(Num) -> integer_to_list(Num); -+ _ -> "unknown" -+ end, -+ {result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}], -+ [{xmlelement, "title", [], -+ [{xmlcdata, -+ translate:translate( -+ Lang, "Messages logging engine settings") ++ " (run-time)"}]}, -+ {xmlelement, "instructions", [], -+ [{xmlcdata, -+ translate:translate( -+ Lang, "Set run-time settings")}]}, -+ % backends -+ {xmlelement, "field", [{"type", "list-single"}, -+ {"label", -+ translate:translate(Lang, "Backend")}, -+ {"var", "backend"}], -+ DBsL}, -+ % dbs -+ {xmlelement, "field", [{"type", "text-multi"}, -+ {"label", -+ translate:translate( -+ Lang, "dbs")}, -+ {"var", "dbs"}], -+ [{xmlelement, "value", [], [{xmlcdata, lists:flatten(io_lib:format("~p.",[DBs]))}]}]}, -+ % default to log -+ {xmlelement, "field", [{"type", "list-single"}, -+ {"label", -+ translate:translate(Lang, "Default")}, -+ {"var", "dolog_default"}], -+ [?DEFVAL(atom_to_list(DLD)), -+ ?LISTLINE(translate:translate(Lang, "Log Messages"), "true"), -+ ?LISTLINE(translate:translate(Lang, "Do Not Log Messages"), "false") -+ ]}, -+ % drop_messages_on_user_removal -+ {xmlelement, "field", [{"type", "list-single"}, -+ {"label", -+ translate:translate(Lang, "Drop messages on user removal")}, -+ {"var", "drop_messages_on_user_removal"}], -+ [?DEFVAL(atom_to_list(MRemoval)), -+ ?LISTLINE(translate:translate(Lang, "Drop"), "true"), -+ ?LISTLINE(translate:translate(Lang, "Do not drop"), "false") -+ ]}, -+ % groupchat -+ {xmlelement, "field", [{"type", "list-single"}, -+ {"label", -+ translate:translate(Lang, "Groupchat messages logging")}, -+ {"var", "groupchat"}], -+ [?DEFVAL(atom_to_list(GroupChat)), -+ ?LISTLINE("all", "all"), -+ ?LISTLINE("none", "none"), -+ ?LISTLINE("send", "send"), -+ ?LISTLINE("half", "half") -+ ]}, -+ % ignore_jids -+ {xmlelement, "field", [{"type", "text-multi"}, -+ {"label", -+ translate:translate( -+ Lang, "Jids/Domains to ignore")}, -+ {"var", "ignore_list"}], -+ [{xmlelement, "value", [], [{xmlcdata, list_to_string(IgnoreJids)}]}]}, -+ % purge older days -+ {xmlelement, "field", [{"type", "text-single"}, -+ {"label", -+ translate:translate( -+ Lang, "Purge messages older than (days)")}, -+ {"var", "purge_older_days"}], -+ [{xmlelement, "value", [], [{xmlcdata, PurgeDays}]}]}, -+ % poll users settings -+ {xmlelement, "field", [{"type", "text-single"}, -+ {"label", -+ translate:translate( -+ Lang, "Poll users settings (seconds)")}, -+ {"var", "poll_users_settings"}], -+ [{xmlelement, "value", [], [{xmlcdata, integer_to_list(PollTime)}]}]} -+ ]}]}. -+ -+get_form(_Host, ["mod_logdb"], #jid{luser = LUser, lserver = LServer} = _Jid, Lang) -> -+ get_user_form(LUser, LServer, Lang); -+get_form(_Host, ["mod_logdb_users", User], _JidFrom, Lang) -> -+ #jid{luser=LUser, lserver=LServer} = jlib:string_to_jid(User), -+ get_user_form(LUser, LServer, Lang); -+get_form(Host, ["mod_logdb_settings"], _JidFrom, Lang) -> -+ get_settings_form(Host, Lang); -+get_form(_Host, Command, _, _Lang) -> -+ ?MYDEBUG("asked for form ~p", [Command]), -+ {error, ?ERR_SERVICE_UNAVAILABLE}. -+ -+check_log_list([Head | Tail]) -> -+ case lists:member($@, Head) of -+ true -> ok; -+ false -> throw(error) -+ end, -+ % this check for Head to be valid jid -+ case jlib:string_to_jid(Head) of -+ error -> -+ throw(error); -+ _ -> -+ check_log_list(Tail) -+ end; -+check_log_list([]) -> -+ ok. -+ -+check_ignore_list([Head | Tail]) -> -+ case lists:member($@, Head) of -+ true -> ok; -+ false -> throw(error) -+ end, -+ % this check for Head to be valid jid -+ case jlib:string_to_jid(Head) of -+ error -> -+ % this check for Head to be valid domain "@domain.org" -+ case lists:nth(1, Head) of -+ $@ -> -+ % TODO: this allows spaces and special characters in Head. May be change to nodeprep? -+ case jlib:nameprep(lists:delete($@, Head)) of -+ error -> throw(error); -+ _ -> check_log_list(Tail) -+ end; -+ _ -> throw(error) -+ end; -+ _ -> -+ check_ignore_list(Tail) -+ end; -+check_ignore_list([]) -> -+ ok. -+ -+parse_users_settings(XData) -> -+ DLD = case lists:keysearch("dolog_default", 1, XData) of -+ {value, {_, [String]}} when String == "true"; String == "false" -> -+ list_to_bool(String); -+ _ -> -+ throw(bad_request) -+ end, -+ DLL = case lists:keysearch("dolog_list", 1, XData) of -+ false -> -+ throw(bad_request); -+ {value, {_, [[]]}} -> -+ []; -+ {value, {_, List1}} -> -+ case catch check_log_list(List1) of -+ error -> -+ throw(bad_request); -+ ok -> -+ List1 -+ end -+ end, -+ DNLL = case lists:keysearch("donotlog_list", 1, XData) of -+ false -> -+ throw(bad_request); -+ {value, {_, [[]]}} -> -+ []; -+ {value, {_, List2}} -> -+ case catch check_log_list(List2) of -+ error -> -+ throw(bad_request); -+ ok -> -+ List2 -+ end -+ end, -+ #user_settings{dolog_default=DLD, -+ dolog_list=DLL, -+ donotlog_list=DNLL}. -+ -+parse_module_settings(XData) -> -+ DLD = case lists:keysearch("dolog_default", 1, XData) of -+ {value, {_, [Str1]}} when Str1 == "true"; Str1 == "false" -> -+ list_to_bool(Str1); -+ _ -> -+ throw(bad_request) -+ end, -+ MRemoval = case lists:keysearch("drop_messages_on_user_removal", 1, XData) of -+ {value, {_, [Str5]}} when Str5 == "true"; Str5 == "false" -> -+ list_to_bool(Str5); -+ _ -> -+ throw(bad_request) -+ end, -+ GroupChat = case lists:keysearch("groupchat", 1, XData) of -+ {value, {_, [Str2]}} when Str2 == "none"; -+ Str2 == "all"; -+ Str2 == "send"; -+ Str2 == "half" -> -+ list_to_atom(Str2); -+ _ -> -+ throw(bad_request) -+ end, -+ Ignore = case lists:keysearch("ignore_list", 1, XData) of -+ {value, {_, List}} -> -+ case catch check_ignore_list(List) of -+ ok -> -+ List; -+ error -> -+ throw(bad_request) -+ end; -+ _ -> -+ throw(bad_request) -+ end, -+ Purge = case lists:keysearch("purge_older_days", 1, XData) of -+ {value, {_, ["never"]}} -> -+ never; -+ {value, {_, [Str3]}} -> -+ case catch list_to_integer(Str3) of -+ {'EXIT', {badarg, _}} -> throw(bad_request); -+ Int1 -> Int1 -+ end; -+ _ -> -+ throw(bad_request) -+ end, -+ Poll = case lists:keysearch("poll_users_settings", 1, XData) of -+ {value, {_, [Str4]}} -> -+ case catch list_to_integer(Str4) of -+ {'EXIT', {badarg, _}} -> throw(bad_request); -+ Int2 -> Int2 -+ end; -+ _ -> -+ throw(bad_request) -+ end, -+ #state{dolog_default=DLD, -+ groupchat=GroupChat, -+ ignore_jids=Ignore, -+ purge_older_days=Purge, -+ drop_messages_on_user_removal=MRemoval, -+ poll_users_settings=Poll}. -+ -+set_form(From, _Host, ["mod_logdb"], _Lang, XData) -> -+ #jid{luser=LUser, lserver=LServer} = From, -+ case catch parse_users_settings(XData) of -+ bad_request -> -+ {error, ?ERR_BAD_REQUEST}; -+ UserSettings -> -+ case mod_logdb:set_user_settings(LUser, LServer, UserSettings) of -+ ok -> -+ {result, []}; -+ error -> -+ {error, ?ERR_INTERNAL_SERVER_ERROR} -+ end -+ end; -+set_form(_From, _Host, ["mod_logdb_users", User], _Lang, XData) -> -+ #jid{luser=LUser, lserver=LServer} = jlib:string_to_jid(User), -+ case catch parse_users_settings(XData) of -+ bad_request -> {error, ?ERR_BAD_REQUEST}; -+ UserSettings -> -+ case mod_logdb:set_user_settings(LUser, LServer, UserSettings) of -+ ok -> -+ {result, []}; -+ error -> -+ {error, ?ERR_INTERNAL_SERVER_ERROR} -+ end -+ end; -+set_form(_From, Host, ["mod_logdb_settings"], _Lang, XData) -> -+ case catch parse_module_settings(XData) of -+ bad_request -> {error, ?ERR_BAD_REQUEST}; -+ Settings -> -+ case mod_logdb:set_module_settings(Host, Settings) of -+ ok -> -+ {result, []}; -+ error -> -+ {error, ?ERR_INTERNAL_SERVER_ERROR} -+ end -+ end; -+set_form(From, _Host, Node, _Lang, XData) -> -+ User = jlib:jid_to_string(jlib:jid_remove_resource(From)), -+ ?MYDEBUG("set form for ~p at ~p XData=~p", [User, Node, XData]), -+ {error, ?ERR_SERVICE_UNAVAILABLE}. -+ -+%adhoc_sm_items(Acc, From, To, Request) -> -+% ?MYDEBUG("adhoc_sm_items Acc=~p From=~p To=~p Request=~p", [Acc, From, To, Request]), -+% Acc. -+ -+%adhoc_sm_commands(Acc, From, To, Request) -> -+% ?MYDEBUG("adhoc_sm_commands Acc=~p From=~p To=~p Request=~p", [Acc, From, To, Request]), -+% Acc. -+ -+get_all_vh_users(Host, Server, Lang) -> -+ case catch ejabberd_auth:get_vh_registered_users(Host) of -+ {'EXIT', _Reason} -> -+ []; -+ Users -> -+ SUsers = lists:sort([{S, U} || {U, S} <- Users]), -+ case length(SUsers) of -+ N when N =< 100 -> -+ lists:map(fun({S, U}) -> -+ ?NODE(U ++ "@" ++ S, "mod_logdb_users/" ++ U ++ "@" ++ S) -+ end, SUsers); -+ N -> -+ NParts = trunc(math:sqrt(N * 0.618)) + 1, -+ M = trunc(N / NParts) + 1, -+ lists:map(fun(K) -> -+ L = K + M - 1, -+ Node = -+ "@" ++ integer_to_list(K) ++ -+ "-" ++ integer_to_list(L), -+ {FS, FU} = lists:nth(K, SUsers), -+ {LS, LU} = -+ if L < N -> lists:nth(L, SUsers); -+ true -> lists:last(SUsers) -+ end, -+ Name = -+ FU ++ "@" ++ FS ++ -+ " -- " ++ -+ LU ++ "@" ++ LS, -+ ?NODE(Name, "mod_logdb_users/" ++ Node) -+ end, lists:seq(1, N, M)) -+ end -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% webadmin hooks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+webadmin_menu(Acc, _Host, Lang) -> -+ [{"messages", ?T("Users Messages")} | Acc]. -+ -+webadmin_user(Acc, User, Server, Lang) -> -+ Sett = get_user_settings(User, Server), -+ Log = -+ case Sett#user_settings.dolog_default of -+ false -> -+ ?INPUTT("submit", "dolog", "Log Messages"); -+ true -> -+ ?INPUTT("submit", "donotlog", "Do Not Log Messages"); -+ _ -> [] -+ end, -+ Acc ++ [?XE("h3", [?ACT("messages/", "Messages"), ?C(" "), Log])]. -+ -+webadmin_page(_, Host, -+ #request{path = ["messages"], -+ q = Query, -+ lang = Lang}) when is_list(Host) -> -+ Res = vhost_messages_stats(Host, Query, Lang), -+ {stop, Res}; -+webadmin_page(_, Host, -+ #request{path = ["messages", Date], -+ q = Query, -+ lang = Lang}) when is_list(Host) -> -+ Res = vhost_messages_stats_at(Host, Query, Lang, Date), -+ {stop, Res}; -+webadmin_page(_, Host, -+ #request{path = ["user", U, "messages"], -+ q = Query, -+ lang = Lang}) -> -+ Res = user_messages_stats(U, Host, Query, Lang), -+ {stop, Res}; -+webadmin_page(_, Host, -+ #request{path = ["user", U, "messages", Date], -+ q = Query, -+ lang = Lang}) -> -+ Res = mod_logdb:user_messages_stats_at(U, Host, Query, Lang, Date), -+ {stop, Res}; -+webadmin_page(Acc, _, _) -> Acc. -+ -+user_parse_query(_, "dolog", User, Server, _Query) -> -+ Sett = get_user_settings(User, Server), -+ % TODO: check returned value -+ set_user_settings(User, Server, Sett#user_settings{dolog_default=true}), -+ {stop, ok}; -+user_parse_query(_, "donotlog", User, Server, _Query) -> -+ Sett = get_user_settings(User, Server), -+ % TODO: check returned value -+ set_user_settings(User, Server, Sett#user_settings{dolog_default=false}), -+ {stop, ok}; -+user_parse_query(Acc, _Action, _User, _Server, _Query) -> -+ Acc. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% webadmin funcs -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+vhost_messages_stats(Server, Query, Lang) -> -+ Res = case catch vhost_messages_parse_query(Server, Query) of -+ {'EXIT', Reason} -> -+ ?ERROR_MSG("~p", [Reason]), -+ error; -+ VResult -> VResult -+ end, -+ {Time, Value} = timer:tc(mod_logdb, get_vhost_stats, [Server]), -+ ?INFO_MSG("get_vhost_stats(~p) elapsed ~p sec", [Server, Time/1000000]), -+ %case get_vhost_stats(Server) of -+ case Value of -+ {'EXIT', CReason} -> -+ ?ERROR_MSG("Failed to get_vhost_stats: ~p", [CReason]), -+ [?XC("h1", ?T("Error occupied while fetching list"))]; -+ {error, GReason} -> -+ ?ERROR_MSG("Failed to get_vhost_stats: ~p", [GReason]), -+ [?XC("h1", ?T("Error occupied while fetching list"))]; -+ {ok, []} -> -+ [?XC("h1", ?T("No logged messages for ") ++ Server)]; -+ {ok, Dates} -> -+ Fun = fun({Date, Count}) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(Server++Date))), -+ ?XE("tr", -+ [?XE("td", [?INPUT("checkbox", "selected", ID)]), -+ ?XE("td", [?AC(Date, Date)]), -+ ?XC("td", integer_to_list(Count)) -+ ]) -+ end, -+ [?XC("h1", ?T("Logged messages for ") ++ Server)] ++ -+ case Res of -+ ok -> [?CT("Submitted"), ?P]; -+ error -> [?CT("Bad format"), ?P]; -+ nothing -> [] -+ end ++ -+ [?XAE("form", [{"action", ""}, {"method", "post"}], -+ [?XE("table", -+ [?XE("thead", -+ [?XE("tr", -+ [?X("td"), -+ ?XCT("td", "Date"), -+ ?XCT("td", "Count") -+ ])]), -+ ?XE("tbody", -+ lists:map(Fun, Dates) -+ )]), -+ ?BR, -+ ?INPUTT("submit", "delete", "Delete Selected") -+ ])] -+ end. -+ -+vhost_messages_stats_at(Server, Query, Lang, Date) -> -+ {Time, Value} = timer:tc(mod_logdb, get_vhost_stats_at, [Server, Date]), -+ ?INFO_MSG("get_vhost_stats_at(~p,~p) elapsed ~p sec", [Server, Date, Time/1000000]), -+ %case get_vhost_stats_at(Server, Date) of -+ case Value of -+ {'EXIT', CReason} -> -+ ?ERROR_MSG("Failed to get_vhost_stats_at: ~p", [CReason]), -+ [?XC("h1", ?T("Error occupied while fetching list"))]; -+ {error, GReason} -> -+ ?ERROR_MSG("Failed to get_vhost_stats_at: ~p", [GReason]), -+ [?XC("h1", ?T("Error occupied while fetching list"))]; -+ {ok, []} -> -+ [?XC("h1", ?T("No logged messages for ") ++ Server ++ ?T(" at ") ++ Date)]; -+ {ok, Users} -> -+ Res = case catch vhost_messages_at_parse_query(Server, Date, Users, Query) of -+ {'EXIT', Reason} -> -+ ?ERROR_MSG("~p", [Reason]), -+ error; -+ VResult -> VResult -+ end, -+ Fun = fun({User, Count}) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(User++Server))), -+ ?XE("tr", -+ [?XE("td", [?INPUT("checkbox", "selected", ID)]), -+ ?XE("td", [?AC("../user/"++User++"/messages/"++Date, User)]), -+ ?XC("td", integer_to_list(Count)) -+ ]) -+ end, -+ [?XC("h1", ?T("Logged messages for ") ++ Server ++ ?T(" at ") ++ Date)] ++ -+ case Res of -+ ok -> [?CT("Submitted"), ?P]; -+ error -> [?CT("Bad format"), ?P]; -+ nothing -> [] -+ end ++ -+ [?XAE("form", [{"action", ""}, {"method", "post"}], -+ [?XE("table", -+ [?XE("thead", -+ [?XE("tr", -+ [?X("td"), -+ ?XCT("td", "User"), -+ ?XCT("td", "Count") -+ ])]), -+ ?XE("tbody", -+ lists:map(Fun, Users) -+ )]), -+ ?BR, -+ ?INPUTT("submit", "delete", "Delete Selected") -+ ])] -+ end. -+ -+user_messages_stats(User, Server, Query, Lang) -> -+ Jid = jlib:jid_to_string({User, Server, ""}), -+ -+ Res = case catch user_messages_parse_query(User, Server, Query) of -+ {'EXIT', Reason} -> -+ ?ERROR_MSG("~p", [Reason]), -+ error; -+ VResult -> VResult -+ end, -+ -+ {Time, Value} = timer:tc(mod_logdb, get_user_stats, [User, Server]), -+ ?INFO_MSG("get_user_stats(~p,~p) elapsed ~p sec", [User, Server, Time/1000000]), -+ -+ case Value of -+ {'EXIT', CReason} -> -+ ?ERROR_MSG("Failed to get_user_stats: ~p", [CReason]), -+ [?XC("h1", ?T("Error occupied while fetching days"))]; -+ {error, GReason} -> -+ ?ERROR_MSG("Failed to get_user_stats: ~p", [GReason]), -+ [?XC("h1", ?T("Error occupied while fetching days"))]; -+ {ok, []} -> -+ [?XC("h1", ?T("No logged messages for ") ++ Jid)]; -+ {ok, Dates} -> -+ Fun = fun({Date, Count}) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(User++Date))), -+ ?XE("tr", -+ [?XE("td", [?INPUT("checkbox", "selected", ID)]), -+ ?XE("td", [?AC(Date, Date)]), -+ ?XC("td", integer_to_list(Count)) -+ ]) -+ %[?AC(Date, Date ++ " (" ++ integer_to_list(Count) ++ ")"), ?BR] -+ end, -+ [?XC("h1", ?T("Logged messages for ") ++ Jid)] ++ -+ case Res of -+ ok -> [?CT("Submitted"), ?P]; -+ error -> [?CT("Bad format"), ?P]; -+ nothing -> [] -+ end ++ -+ [?XAE("form", [{"action", ""}, {"method", "post"}], -+ [?XE("table", -+ [?XE("thead", -+ [?XE("tr", -+ [?X("td"), -+ ?XCT("td", "Date"), -+ ?XCT("td", "Count") -+ ])]), -+ ?XE("tbody", -+ lists:map(Fun, Dates) -+ )]), -+ ?BR, -+ ?INPUTT("submit", "delete", "Delete Selected") -+ ])] -+ end. -+ -+search_user_nick(User, List) -> -+ case lists:keysearch(User, 1, List) of -+ {value,{User, []}} -> -+ nothing; -+ {value,{User, Nick}} -> -+ Nick; -+ false -> -+ nothing -+ end. -+ -+user_messages_stats_at(User, Server, Query, Lang, Date) -> -+ Jid = jlib:jid_to_string({User, Server, ""}), -+ -+ {Time, Value} = timer:tc(mod_logdb, get_user_messages_at, [User, Server, Date]), -+ ?INFO_MSG("get_user_messages_at(~p,~p,~p) elapsed ~p sec", [User, Server, Date, Time/1000000]), -+ case Value of -+ {'EXIT', CReason} -> -+ ?ERROR_MSG("Failed to get_user_messages_at: ~p", [CReason]), -+ [?XC("h1", ?T("Error occupied while fetching messages"))]; -+ {error, GReason} -> -+ ?ERROR_MSG("Failed to get_user_messages_at: ~p", [GReason]), -+ [?XC("h1", ?T("Error occupied while fetching messages"))]; -+ {ok, []} -> -+ [?XC("h1", ?T("No logged messages for ") ++ Jid ++ ?T(" at ") ++ Date)]; -+ {ok, User_messages} -> -+ Res = case catch user_messages_at_parse_query(Server, -+ Date, -+ User_messages, -+ Query) of -+ {'EXIT', Reason} -> -+ ?ERROR_MSG("~p", [Reason]), -+ error; -+ VResult -> VResult -+ end, -+ -+ UR = ejabberd_hooks:run_fold(roster_get, Server, [], [{User, Server}]), -+ UserRoster = -+ lists:map(fun(Item) -> -+ {jlib:jid_to_string(Item#roster.jid), Item#roster.name} -+ end, UR), -+ -+ UniqUsers = lists:foldl(fun(#msg{peer_name=PName, peer_server=PServer}, List) -> -+ ToAdd = PName++"@"++PServer, -+ case lists:member(ToAdd, List) of -+ true -> List; -+ false -> lists:append([ToAdd], List) -+ end -+ end, [], User_messages), -+ -+ % Users to filter (sublist of UniqUsers) -+ CheckedUsers = case lists:keysearch("filter", 1, Query) of -+ {value, _} -> -+ lists:filter(fun(UFUser) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(UFUser))), -+ lists:member({"selected", ID}, Query) -+ end, UniqUsers); -+ false -> [] -+ end, -+ -+ % UniqUsers in html (noone selected -> everyone selected) -+ Users = lists:map(fun(UHUser) -> -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(UHUser))), -+ Input = case lists:member(UHUser, CheckedUsers) of -+ true -> [?INPUTC("checkbox", "selected", ID)]; -+ false when CheckedUsers == [] -> [?INPUTC("checkbox", "selected", ID)]; -+ false -> [?INPUT("checkbox", "selected", ID)] -+ end, -+ Nick = -+ case search_user_nick(UHUser, UserRoster) of -+ nothing -> ""; -+ N -> " ("++ N ++")" -+ end, -+ ?XE("tr", -+ [?XE("td", Input), -+ ?XC("td", UHUser++Nick)]) -+ end, lists:sort(UniqUsers)), -+ % Messages to show (based on Users) -+ User_messages_filtered = case CheckedUsers of -+ [] -> User_messages; -+ _ -> lists:filter(fun(#msg{peer_name=PName, peer_server=PServer}) -> -+ lists:member(PName++"@"++PServer, CheckedUsers) -+ end, User_messages) -+ end, -+ -+ Msgs_Fun = fun(#msg{timestamp=Timestamp, -+ subject=Subject, -+ direction=Direction, -+ peer_name=PName, peer_server=PServer, peer_resource=PRes, -+ type=Type, -+ body=Body}) -> -+ TextRaw = case Subject of -+ "" -> Body; -+ _ -> [?T("Subject"),": ",Subject,"
    ", Body] -+ end, -+ ID = jlib:encode_base64(binary_to_list(term_to_binary(Timestamp))), -+ % replace \n with
    -+ Text = lists:map(fun(10) -> "
    "; -+ (A) -> A -+ end, TextRaw), -+ Resource = case PRes of -+ [] -> []; -+ undefined -> []; -+ R -> "/" ++ R -+ end, -+ UserNick = -+ case search_user_nick(PName++"@"++PServer, UserRoster) of -+ nothing when PServer == Server -> -+ PName; -+ nothing when Type == "groupchat", Direction == from -> -+ PName++"@"++PServer++Resource; -+ nothing -> -+ PName++"@"++PServer; -+ N -> N -+ end, -+ ?XE("tr", -+ [?XE("td", [?INPUT("checkbox", "selected", ID)]), -+ ?XC("td", convert_timestamp(Timestamp)), -+ ?XC("td", atom_to_list(Direction)++": "++UserNick), -+ ?XC("td", Text)]) -+ end, -+ % Filtered user messages in html -+ Msgs = lists:map(Msgs_Fun, lists:sort(User_messages_filtered)), -+ -+ [?XC("h1", ?T("Logged messages for ") ++ Jid ++ ?T(" at ") ++ Date)] ++ -+ case Res of -+ ok -> [?CT("Submitted"), ?P]; -+ error -> [?CT("Bad format"), ?P]; -+ nothing -> [] -+ end ++ -+ [?XAE("form", [{"action", ""}, {"method", "post"}], -+ [?XE("table", -+ [?XE("thead", -+ [?X("td"), -+ ?XCT("td", "User") -+ ] -+ ), -+ ?XE("tbody", -+ Users -+ )]), -+ ?INPUTT("submit", "filter", "Filter Selected") -+ ] ++ -+ [?XE("table", -+ [?XE("thead", -+ [?XE("tr", -+ [?X("td"), -+ ?XCT("td", "Date, Time"), -+ ?XCT("td", "Direction: Jid"), -+ ?XCT("td", "Body") -+ ])]), -+ ?XE("tbody", -+ Msgs -+ )]), -+ ?INPUTT("submit", "delete", "Delete Selected"), -+ ?BR -+ ] -+ )] -+ end. ---- mod_logdb.hrl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ mod_logdb.hrl 2009-02-05 19:21:02.000000000 +0200 -@@ -0,0 +1,35 @@ -+%%%---------------------------------------------------------------------- -+%%% File : mod_logdb.hrl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : -+%%% Version : trunk -+%%% Id : $Id: mod_logdb.hrl 1163 2008-09-15 11:12:08Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-define(logdb_debug, true). -+ -+-ifdef(logdb_debug). -+-define(MYDEBUG(Format, Args), io:format("D(~p:~p:~p) : "++Format++"~n", -+ [calendar:local_time(),?MODULE,?LINE]++Args)). -+-else. -+-define(MYDEBUG(_F,_A),[]). -+-endif. -+ -+-record(msg, {timestamp, -+ owner_name, -+ peer_name, peer_server, peer_resource, -+ direction, -+ type, subject, -+ body}). -+ -+-record(user_settings, {owner_name, -+ dolog_default, -+ dolog_list=[], -+ donotlog_list=[]}). -+ -+-define(INPUTC(Type, Name, Value), -+ ?XA("input", [{"type", Type}, -+ {"name", Name}, -+ {"value", Value}, -+ {"checked", "true"}])). ---- mod_logdb_mnesia.erl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ mod_logdb_mnesia.erl 2009-02-05 19:19:59.000000000 +0200 -@@ -0,0 +1,546 @@ -+%%%---------------------------------------------------------------------- -+%%% File : mod_logdb_mnesia.erl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : mnesia backend for mod_logdb -+%%% Version : trunk -+%%% Id : $Id: mod_logdb_mnesia.erl 1169 2008-09-16 12:14:36Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-module(mod_logdb_mnesia). -+-author('o.palij@gmail.com'). -+ -+-include("mod_logdb.hrl"). -+-include("ejabberd.hrl"). -+-include("jlib.hrl"). -+ -+-behaviour(gen_logdb). -+-behaviour(gen_server). -+ -+% gen_server -+-export([code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2]). -+% gen_mod -+-export([start/2, stop/1]). -+% gen_logdb -+-export([log_message/2, -+ rebuild_stats/1, -+ rebuild_stats_at/2, -+ delete_messages_by_user_at/3, delete_all_messages_by_user_at/3, delete_messages_at/2, -+ get_vhost_stats/1, get_vhost_stats_at/2, get_user_stats/2, get_user_messages_at/3, -+ get_dates/1, -+ get_users_settings/1, get_user_settings/2, set_user_settings/3, -+ drop_user/2]). -+ -+-define(PROCNAME, mod_logdb_mnesia). -+-define(CALL_TIMEOUT, 10000). -+ -+-record(state, {vhost}). -+ -+-record(stats, {user, at, count}). -+ -+prefix() -> -+ "logdb_". -+ -+suffix(VHost) -> -+ "_" ++ VHost. -+ -+stats_table(VHost) -> -+ list_to_atom(prefix() ++ "stats" ++ suffix(VHost)). -+ -+table_name(VHost, Date) -> -+ list_to_atom(prefix() ++ "messages_" ++ Date ++ suffix(VHost)). -+ -+settings_table(VHost) -> -+ list_to_atom(prefix() ++ "settings" ++ suffix(VHost)). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_mod callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+start(VHost, Opts) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:start({local, Proc}, ?MODULE, [VHost, Opts], []). -+ -+stop(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {stop}, ?CALL_TIMEOUT). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_server callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+init([VHost, _Opts]) -> -+ case mnesia:system_info(is_running) of -+ yes -> -+ ok = create_stats_table(VHost), -+ ok = create_settings_table(VHost), -+ {ok, #state{vhost=VHost}}; -+ no -> -+ ?ERROR_MSG("Mnesia not running", []), -+ {stop, db_connection_failed}; -+ Status -> -+ ?ERROR_MSG("Mnesia status: ~p", [Status]), -+ {stop, db_connection_failed} -+ end. -+ -+handle_call({log_message, Msg}, _From, #state{vhost=VHost}=State) -> -+ {reply, log_message_int(VHost, Msg), State}; -+handle_call({rebuild_stats}, _From, #state{vhost=VHost}=State) -> -+ {atomic, ok} = delete_nonexistent_stats(VHost), -+ Reply = -+ lists:foreach(fun(Date) -> -+ rebuild_stats_at_int(VHost, Date) -+ end, get_dates_int(VHost)), -+ {reply, Reply, State}; -+handle_call({rebuild_stats_at, Date}, _From, #state{vhost=VHost}=State) -> -+ Reply = rebuild_stats_at_int(VHost, Date), -+ {reply, Reply, State}; -+handle_call({delete_messages_by_user_at, Msgs, Date}, _From, #state{vhost=VHost}=State) -> -+ Table = table_name(VHost, Date), -+ Fun = fun() -> -+ lists:foreach( -+ fun(Msg) -> -+ mnesia:write_lock_table(stats_table(VHost)), -+ mnesia:write_lock_table(Table), -+ mnesia:delete_object(Table, Msg, write) -+ end, Msgs) -+ end, -+ DRez = case mnesia:transaction(Fun) of -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to delete_messages_by_user_at at ~p for ~p: ~p", [Date, VHost, Reason]), -+ error; -+ _ -> -+ ok -+ end, -+ Reply = -+ case rebuild_stats_at_int(VHost, Date) of -+ error -> -+ error; -+ ok -> -+ DRez -+ end, -+ {reply, Reply, State}; -+handle_call({delete_all_messages_by_user_at, User, Date}, _From, #state{vhost=VHost}=State) -> -+ {reply, delete_all_messages_by_user_at_int(User, VHost, Date), State}; -+handle_call({delete_messages_at, Date}, _From, #state{vhost=VHost}=State) -> -+ Reply = -+ case mnesia:delete_table(table_name(VHost, Date)) of -+ {atomic, ok} -> -+ delete_stats_by_vhost_at_int(VHost, Date); -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to delete_messages_at for ~p at ~p", [VHost, Date, Reason]), -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats}, _From, #state{vhost=VHost}=State) -> -+ Fun = fun(#stats{at=Date, count=Count}, Stats) -> -+ case lists:keysearch(Date, 1, Stats) of -+ false -> -+ lists:append(Stats, [{Date, Count}]); -+ {value, {_, TempCount}} -> -+ lists:keyreplace(Date, 1, Stats, {Date, TempCount+Count}) -+ end -+ end, -+ Reply = -+ case mnesia:transaction(fun() -> -+ mnesia:foldl(Fun, [], stats_table(VHost)) -+ end) of -+ {atomic, Result} -> {ok, mod_logdb:sort_stats(Result)}; -+ {aborted, Reason} -> {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats_at, Date}, _From, #state{vhost=VHost}=State) -> -+ Fun = fun() -> -+ Pat = #stats{user='$1', at=Date, count='$2'}, -+ mnesia:select(stats_table(VHost), [{Pat, [], [['$1', '$2']]}]) -+ end, -+ Reply = -+ case mnesia:transaction(Fun) of -+ {atomic, Result} -> -+ {ok, lists:reverse(lists:keysort(2, [{User, Count} || [User, Count] <- Result]))}; -+ {aborted, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_user_stats, User}, _From, #state{vhost=VHost}=State) -> -+ {reply, get_user_stats_int(User, VHost), State}; -+handle_call({get_user_messages_at, User, Date}, _From, #state{vhost=VHost}=State) -> -+ Reply = -+ case mnesia:transaction(fun() -> -+ Pat = #msg{owner_name=User, _='_'}, -+ mnesia:select(table_name(VHost, Date), -+ [{Pat, [], ['$_']}]) -+ end) of -+ {atomic, Result} -> {ok, Result}; -+ {aborted, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_dates}, _From, #state{vhost=VHost}=State) -> -+ {reply, get_dates_int(VHost), State}; -+handle_call({get_users_settings}, _From, #state{vhost=VHost}=State) -> -+ Reply = mnesia:dirty_match_object(settings_table(VHost), #user_settings{_='_'}), -+ {reply, {ok, Reply}, State}; -+handle_call({get_user_settings, User}, _From, #state{vhost=VHost}=State) -> -+ Reply = -+ case mnesia:dirty_match_object(settings_table(VHost), #user_settings{owner_name=User, _='_'}) of -+ [] -> []; -+ [Setting] -> -+ Setting -+ end, -+ {reply, Reply, State}; -+handle_call({set_user_settings, _User, Set}, _From, #state{vhost=VHost}=State) -> -+ ?MYDEBUG("~p~n~p", [settings_table(VHost), Set]), -+ Reply = mnesia:dirty_write(settings_table(VHost), Set), -+ ?MYDEBUG("~p", [Reply]), -+ {reply, Reply, State}; -+handle_call({drop_user, User}, _From, #state{vhost=VHost}=State) -> -+ {ok, Dates} = get_user_stats_int(User, VHost), -+ MDResult = lists:map(fun({Date, _}) -> -+ delete_all_messages_by_user_at_int(User, VHost, Date) -+ end, Dates), -+ SDResult = delete_user_settings_int(User, VHost), -+ Reply = -+ case lists:all(fun(Result) when Result == ok -> -+ true; -+ (Result) when Result == error -> -+ false -+ end, lists:append(MDResult, [SDResult])) of -+ true -> -+ ok; -+ false -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({stop}, _From, State) -> -+ {stop, normal, ok, State}; -+handle_call(Msg, _From, State) -> -+ ?INFO_MSG("Got call Msg: ~p, State: ~p", [Msg, State]), -+ {noreply, State}. -+ -+handle_cast(Msg, State) -> -+ ?INFO_MSG("Got cast Msg:~p, State:~p", [Msg, State]), -+ {noreply, State}. -+ -+handle_info(Info, State) -> -+ ?INFO_MSG("Got Info:~p, State:~p", [Info, State]), -+ {noreply, State}. -+ -+terminate(_Reason, _State) -> -+ ok. -+ -+code_change(_OldVsn, State, _Extra) -> -+ {ok, State}. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+log_message(VHost, Msg) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {log_message, Msg}, ?CALL_TIMEOUT). -+rebuild_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {rebuild_stats}, ?CALL_TIMEOUT). -+rebuild_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {rebuild_stats_at, Date}, ?CALL_TIMEOUT). -+delete_messages_by_user_at(VHost, Msgs, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_by_user_at, Msgs, Date}, ?CALL_TIMEOUT). -+delete_all_messages_by_user_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_all_messages_by_user_at, User, Date}, ?CALL_TIMEOUT). -+delete_messages_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_at, Date}, ?CALL_TIMEOUT). -+get_vhost_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats}, ?CALL_TIMEOUT). -+get_vhost_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats_at, Date}, ?CALL_TIMEOUT). -+get_user_stats(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_stats, User}, ?CALL_TIMEOUT). -+get_user_messages_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_messages_at, User, Date}, ?CALL_TIMEOUT). -+get_dates(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_dates}, ?CALL_TIMEOUT). -+get_user_settings(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_settings, User}, ?CALL_TIMEOUT). -+get_users_settings(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_users_settings}, ?CALL_TIMEOUT). -+set_user_settings(User, VHost, Set) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {set_user_settings, User, Set}, ?CALL_TIMEOUT). -+drop_user(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {drop_user, User}, ?CALL_TIMEOUT). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+log_message_int(VHost, #msg{timestamp=Timestamp}=Msg) -> -+ Date = mod_logdb:convert_timestamp_brief(Timestamp), -+ -+ ATable = table_name(VHost, Date), -+ Fun = fun() -> -+ mnesia:write_lock_table(ATable), -+ mnesia:write(ATable, Msg, write) -+ end, -+ % log message, increment stats for both users -+ case mnesia:transaction(Fun) of -+ % if table does not exists - create it and try to log message again -+ {aborted,{no_exists, _Table}} -> -+ case create_msg_table(VHost, Date) of -+ {aborted, CReason} -> -+ ?ERROR_MSG("Failed to log message: ~p", [CReason]), -+ error; -+ {atomic, ok} -> -+ ?MYDEBUG("Created msg table for ~p at ~p", [VHost, Date]), -+ log_message_int(VHost, Msg) -+ end; -+ {aborted, TReason} -> -+ ?ERROR_MSG("Failed to log message: ~p", [TReason]), -+ error; -+ {atomic, _} -> -+ ?MYDEBUG("Logged ok for ~p, peer: ~p", [Msg#msg.owner_name++"@"++VHost, -+ Msg#msg.peer_name++"@"++Msg#msg.peer_server]), -+ increment_user_stats(Msg#msg.owner_name, VHost, Date) -+ end. -+ -+increment_user_stats(Owner, VHost, Date) -> -+ Fun = fun() -> -+ Pat = #stats{user=Owner, at=Date, count='$1'}, -+ mnesia:write_lock_table(stats_table(VHost)), -+ case mnesia:select(stats_table(VHost), [{Pat, [], ['$_']}]) of -+ [] -> -+ mnesia:write(stats_table(VHost), -+ #stats{user=Owner, -+ at=Date, -+ count=1}, -+ write); -+ [Stats] -> -+ mnesia:delete_object(stats_table(VHost), -+ #stats{user=Owner, -+ at=Date, -+ count=Stats#stats.count}, -+ write), -+ New = Stats#stats{count = Stats#stats.count+1}, -+ if -+ New#stats.count > 0 -> mnesia:write(stats_table(VHost), -+ New, -+ write); -+ true -> ok -+ end -+ end -+ end, -+ case mnesia:transaction(Fun) of -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to update stats for ~s@~s: ~p", [Owner, VHost, Reason]), -+ error; -+ {atomic, _} -> -+ ?MYDEBUG("Updated stats for ~s@~s", [Owner, VHost]), -+ ok -+ end. -+ -+get_dates_int(VHost) -> -+ Tables = mnesia:system_info(tables), -+ lists:foldl(fun(ATable, Dates) -> -+ Table = atom_to_list(ATable), -+ case regexp:match(Table, VHost++"$") of -+ {match, _, _} -> -+ case regexp:match(Table,"_[0-9]+-[0-9]+-[0-9]+_") of -+ {match, S, E} -> -+ lists:append(Dates, [lists:sublist(Table,S+1,E-2)]); -+ nomatch -> -+ Dates -+ end; -+ nomatch -> -+ Dates -+ end -+ end, [], Tables). -+ -+rebuild_stats_at_int(VHost, Date) -> -+ Table = table_name(VHost, Date), -+ STable = stats_table(VHost), -+ CFun = fun(Msg, Stats) -> -+ Owner = Msg#msg.owner_name, -+ case lists:keysearch(Owner, 1, Stats) of -+ {value, {_, Count}} -> -+ lists:keyreplace(Owner, 1, Stats, {Owner, Count + 1}); -+ false -> -+ lists:append(Stats, [{Owner, 1}]) -+ end -+ end, -+ DFun = fun(#stats{at=SDate} = Stat, _Acc) -+ when SDate == Date -> -+ mnesia:delete_object(stats_table(VHost), Stat, write); -+ (_Stat, _Acc) -> ok -+ end, -+ % TODO: Maybe unregister hooks ? -+ case mnesia:transaction(fun() -> -+ mnesia:write_lock_table(Table), -+ mnesia:write_lock_table(STable), -+ % Calc stats for VHost at Date -+ case mnesia:foldl(CFun, [], Table) of -+ [] -> empty; -+ AStats -> -+ % Delete all stats for VHost at Date -+ mnesia:foldl(DFun, [], STable), -+ % Write new calc'ed stats -+ lists:foreach(fun({Owner, Count}) -> -+ WStat = #stats{user=Owner, at=Date, count=Count}, -+ mnesia:write(stats_table(VHost), WStat, write) -+ end, AStats), -+ ok -+ end -+ end) of -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to rebuild_stats_at for ~p at ~p: ~p", [VHost, Date, Reason]), -+ error; -+ {atomic, ok} -> -+ ok; -+ {atomic, empty} -> -+ {atomic,ok} = mnesia:delete_table(Table), -+ ?MYDEBUG("Dropped table at ~p", [Date]), -+ ok -+ end. -+ -+delete_nonexistent_stats(VHost) -> -+ Dates = get_dates_int(VHost), -+ mnesia:transaction(fun() -> -+ mnesia:foldl(fun(#stats{at=Date} = Stat, _Acc) -> -+ case lists:member(Date, Dates) of -+ false -> mnesia:delete_object(Stat); -+ true -> ok -+ end -+ end, ok, stats_table(VHost)) -+ end). -+ -+delete_stats_by_vhost_at_int(VHost, Date) -> -+ StatsDelete = fun(#stats{at=SDate} = Stat, _Acc) -+ when SDate == Date -> -+ mnesia:delete_object(stats_table(VHost), Stat, write), -+ ok; -+ (_Msg, _Acc) -> ok -+ end, -+ case mnesia:transaction(fun() -> -+ mnesia:write_lock_table(stats_table(VHost)), -+ mnesia:foldl(StatsDelete, ok, stats_table(VHost)) -+ end) of -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to update stats at ~p for ~p: ~p", [Date, VHost, Reason]), -+ rebuild_stats_at_int(VHost, Date); -+ _ -> -+ ?INFO_MSG("Updated stats at ~p for ~p", [Date, VHost]), -+ ok -+ end. -+ -+get_user_stats_int(User, VHost) -> -+ case mnesia:transaction(fun() -> -+ Pat = #stats{user=User, at='$1', count='$2'}, -+ mnesia:select(stats_table(VHost), [{Pat, [], [['$1', '$2']]}]) -+ end) of -+ {atomic, Result} -> -+ {ok, mod_logdb:sort_stats([{Date, Count} || [Date, Count] <- Result])}; -+ {aborted, Reason} -> -+ {error, Reason} -+ end. -+ -+delete_all_messages_by_user_at_int(User, VHost, Date) -> -+ Table = table_name(VHost, Date), -+ MsgDelete = fun(#msg{owner_name=Owner} = Msg, _Acc) -+ when Owner == User -> -+ mnesia:delete_object(Table, Msg, write), -+ ok; -+ (_Msg, _Acc) -> ok -+ end, -+ DRez = case mnesia:transaction(fun() -> -+ mnesia:foldl(MsgDelete, ok, Table) -+ end) of -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to delete_all_messages_by_user_at for ~p@~p at ~p: ~p", [User, VHost, Date, Reason]), -+ error; -+ _ -> -+ ok -+ end, -+ case rebuild_stats_at_int(VHost, Date) of -+ error -> -+ error; -+ ok -> -+ DRez -+ end. -+ -+delete_user_settings_int(User, VHost) -> -+ STable = settings_table(VHost), -+ case mnesia:dirty_match_object(STable, #user_settings{owner_name=User, _='_'}) of -+ [] -> -+ ok; -+ [UserSettings] -> -+ mnesia:dirty_delete_object(STable, UserSettings) -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% tables internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+create_stats_table(VHost) -> -+ SName = stats_table(VHost), -+ case mnesia:create_table(SName, -+ [{disc_only_copies, [node()]}, -+ {type, bag}, -+ {attributes, record_info(fields, stats)}, -+ {record_name, stats} -+ ]) of -+ {atomic, ok} -> -+ ?MYDEBUG("Created stats table for ~p", [VHost]), -+ lists:foreach(fun(Date) -> -+ rebuild_stats_at_int(VHost, Date) -+ end, get_dates_int(VHost)), -+ ok; -+ {aborted, {already_exists, _}} -> -+ ?MYDEBUG("Stats table for ~p already exists", [VHost]), -+ ok; -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to create stats table: ~p", [Reason]), -+ error -+ end. -+ -+create_settings_table(VHost) -> -+ SName = settings_table(VHost), -+ case mnesia:create_table(SName, -+ [{disc_copies, [node()]}, -+ {type, set}, -+ {attributes, record_info(fields, user_settings)}, -+ {record_name, user_settings} -+ ]) of -+ {atomic, ok} -> -+ ?MYDEBUG("Created settings table for ~p", [VHost]), -+ ok; -+ {aborted, {already_exists, _}} -> -+ ?MYDEBUG("Settings table for ~p already exists", [VHost]), -+ ok; -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to create settings table: ~p", [Reason]), -+ error -+ end. -+ -+create_msg_table(VHost, Date) -> -+ mnesia:create_table( -+ table_name(VHost, Date), -+ [{disc_only_copies, [node()]}, -+ {type, bag}, -+ {attributes, record_info(fields, msg)}, -+ {record_name, msg}]). ---- mod_logdb_mysql.erl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ mod_logdb_mysql.erl 2009-02-05 19:20:23.000000000 +0200 -@@ -0,0 +1,1052 @@ -+%%%---------------------------------------------------------------------- -+%%% File : mod_logdb_mysql.erl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : MySQL backend for mod_logdb -+%%% Version : trunk -+%%% Id : $Id: mod_logdb_mysql.erl 1253 2009-02-02 11:10:03Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-module(mod_logdb_mysql). -+-author('o.palij@gmail.com'). -+ -+-include("mod_logdb.hrl"). -+-include("ejabberd.hrl"). -+-include("jlib.hrl"). -+ -+-behaviour(gen_logdb). -+-behaviour(gen_server). -+ -+% gen_server -+-export([code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2]). -+% gen_mod -+-export([start/2, stop/1]). -+% gen_logdb -+-export([log_message/2, -+ rebuild_stats/1, -+ rebuild_stats_at/2, -+ delete_messages_by_user_at/3, delete_all_messages_by_user_at/3, delete_messages_at/2, -+ get_vhost_stats/1, get_vhost_stats_at/2, get_user_stats/2, get_user_messages_at/3, -+ get_dates/1, -+ get_users_settings/1, get_user_settings/2, set_user_settings/3, -+ drop_user/2]). -+ -+% gen_server call timeout -+-define(CALL_TIMEOUT, 30000). -+-define(MYSQL_TIMEOUT, 60000). -+-define(INDEX_SIZE, integer_to_list(170)). -+-define(PROCNAME, mod_logdb_mysql). -+ -+-import(mod_logdb, [list_to_bool/1, bool_to_list/1, -+ list_to_string/1, string_to_list/1, -+ convert_timestamp_brief/1]). -+ -+-record(state, {dbref, vhost, server, port, db, user, password}). -+ -+% replace "." with "_" -+escape_vhost(VHost) -> lists:map(fun(46) -> 95; -+ (A) -> A -+ end, VHost). -+prefix() -> -+ "`logdb_". -+ -+suffix(VHost) -> -+ "_" ++ escape_vhost(VHost) ++ "`". -+ -+messages_table(VHost, Date) -> -+ prefix() ++ "messages_" ++ Date ++ suffix(VHost). -+ -+stats_table(VHost) -> -+ prefix() ++ "stats" ++ suffix(VHost). -+ -+temp_table(VHost) -> -+ prefix() ++ "temp" ++ suffix(VHost). -+ -+settings_table(VHost) -> -+ prefix() ++ "settings" ++ suffix(VHost). -+ -+users_table(VHost) -> -+ prefix() ++ "users" ++ suffix(VHost). -+servers_table(VHost) -> -+ prefix() ++ "servers" ++ suffix(VHost). -+resources_table(VHost) -> -+ prefix() ++ "resources" ++ suffix(VHost). -+ -+ets_users_table(VHost) -> list_to_atom("logdb_users_" ++ VHost). -+ets_servers_table(VHost) -> list_to_atom("logdb_servers_" ++ VHost). -+ets_resources_table(VHost) -> list_to_atom("logdb_resources_" ++ VHost). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_mod callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+start(VHost, Opts) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:start({local, Proc}, ?MODULE, [VHost, Opts], []). -+ -+stop(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {stop}, ?CALL_TIMEOUT). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_server callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+init([VHost, Opts]) -> -+ crypto:start(), -+ -+ Server = gen_mod:get_opt(server, Opts, "localhost"), -+ Port = gen_mod:get_opt(port, Opts, 3306), -+ DB = gen_mod:get_opt(db, Opts, "logdb"), -+ User = gen_mod:get_opt(user, Opts, "root"), -+ Password = gen_mod:get_opt(password, Opts, ""), -+ -+ St = #state{vhost=VHost, -+ server=Server, port=Port, db=DB, -+ user=User, password=Password}, -+ -+ case open_mysql_connection(St) of -+ {ok, DBRef} -> -+ State = St#state{dbref=DBRef}, -+ ok = create_stats_table(State), -+ ok = create_settings_table(State), -+ ok = create_users_table(State), -+ % clear ets cache every ... -+ timer:send_interval(timer:hours(12), clear_ets_tables), -+ ok = create_servers_table(State), -+ ok = create_resources_table(State), -+ erlang:monitor(process, DBRef), -+ {ok, State}; -+ {error, Reason} -> -+ ?ERROR_MSG("MySQL connection failed: ~p~n", [Reason]), -+ {stop, db_connection_failed} -+ end. -+ -+open_mysql_connection(#state{server=Server, port=Port, db=DB, -+ user=DBUser, password=Password} = _State) -> -+ LogFun = fun(debug, _Format, _Argument) -> -+ %?MYDEBUG(Format, Argument); -+ ok; -+ (error, Format, Argument) -> -+ ?ERROR_MSG(Format, Argument); -+ (Level, Format, Argument) -> -+ ?MYDEBUG("MySQL (~p)~n", [Level]), -+ ?MYDEBUG(Format, Argument) -+ end, -+ mysql_conn:start(Server, Port, DBUser, Password, DB, LogFun). -+ -+close_mysql_connection(DBRef) -> -+ ?MYDEBUG("Closing ~p mysql connection", [DBRef]), -+ mysql_conn:stop(DBRef). -+ -+handle_call({log_message, Msg}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Date = convert_timestamp_brief(Msg#msg.timestamp), -+ -+ Table = messages_table(VHost, Date), -+ Owner_id = get_user_id(DBRef, VHost, Msg#msg.owner_name), -+ Peer_name_id = get_user_id(DBRef, VHost, Msg#msg.peer_name), -+ Peer_server_id = get_server_id(DBRef, VHost, Msg#msg.peer_server), -+ Peer_resource_id = get_resource_id(DBRef, VHost, Msg#msg.peer_resource), -+ -+ Query = ["INSERT INTO ",Table," ", -+ "(owner_id,", -+ "peer_name_id,", -+ "peer_server_id,", -+ "peer_resource_id,", -+ "direction,", -+ "type,", -+ "subject,", -+ "body,", -+ "timestamp) ", -+ "VALUES ", -+ "('", Owner_id, "',", -+ "'", Peer_name_id, "',", -+ "'", Peer_server_id, "',", -+ "'", Peer_resource_id, "',", -+ "'", atom_to_list(Msg#msg.direction), "',", -+ "'", Msg#msg.type, "',", -+ "'", ejabberd_odbc:escape(Msg#msg.subject), "',", -+ "'", ejabberd_odbc:escape(Msg#msg.body), "',", -+ "'", Msg#msg.timestamp, "');"], -+ -+ Reply = -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Logged ok for ~p, peer: ~p", [Msg#msg.owner_name++"@"++VHost, -+ Msg#msg.peer_name++"@"++Msg#msg.peer_server]), -+ increment_user_stats(DBRef, Msg#msg.owner_name, Owner_id, VHost, Peer_name_id, Peer_server_id, Date); -+ {error, Reason} -> -+ case regexp:match(Reason, "#42S02") of -+ % Table doesn't exist -+ {match, _, _} -> -+ case create_msg_table(DBRef, VHost, Date) of -+ error -> -+ error; -+ ok -> -+ {updated, _} = sql_query_internal(DBRef, Query), -+ increment_user_stats(DBRef, Msg#msg.owner_name, Owner_id, VHost, Peer_name_id, Peer_server_id, Date) -+ end; -+ _ -> -+ ?ERROR_MSG("Failed to log message: ~p", [Reason]), -+ error -+ end -+ end, -+ {reply, Reply, State}; -+handle_call({rebuild_stats_at, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Reply = rebuild_stats_at_int(DBRef, VHost, Date), -+ {reply, Reply, State}; -+handle_call({delete_messages_by_user_at, [], _Date}, _From, State) -> -+ {reply, error, State}; -+handle_call({delete_messages_by_user_at, Msgs, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Temp = lists:flatmap(fun(#msg{timestamp=Timestamp} = _Msg) -> -+ ["\"",Timestamp,"\"",","] -+ end, Msgs), -+ -+ Temp1 = lists:append([lists:sublist(Temp, length(Temp)-1), ");"]), -+ -+ Query = ["DELETE FROM ",messages_table(VHost, Date)," ", -+ "WHERE timestamp IN (", Temp1], -+ -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {updated, Aff} -> -+ ?MYDEBUG("Aff=~p", [Aff]), -+ rebuild_stats_at_int(DBRef, VHost, Date); -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({delete_all_messages_by_user_at, User, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ ok = delete_all_messages_by_user_at_int(DBRef, User, VHost, Date), -+ ok = delete_stats_by_user_at_int(DBRef, User, VHost, Date), -+ {reply, ok, State}; -+handle_call({delete_messages_at, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Reply = -+ case sql_query_internal(DBRef, ["DROP TABLE ",messages_table(VHost, Date),";"]) of -+ {updated, _} -> -+ Query = ["DELETE FROM ",stats_table(VHost)," " -+ "WHERE at=\"",Date,"\";"], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ok; -+ {error, _} -> -+ error -+ end; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["SELECT at, sum(count) ", -+ "FROM ",SName," ", -+ "GROUP BY at ", -+ "ORDER BY DATE(at) DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, [ {Date, list_to_integer(Count)} || [Date, Count] <- Result ]}; -+ {error, Reason} -> -+ % TODO: Duplicate error message ? -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats_at, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["SELECT username, sum(count) AS allcount ", -+ "FROM ",SName," ", -+ "JOIN ",users_table(VHost)," ON owner_id=user_id " -+ "WHERE at=\"",Date,"\" " -+ "GROUP BY username ", -+ "ORDER BY allcount DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, lists:reverse( -+ lists:keysort(2, -+ [ {User, list_to_integer(Count)} || [User, Count] <- Result]))}; -+ {error, Reason} -> -+ % TODO: -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_user_stats, User}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ {reply, get_user_stats_int(DBRef, User, VHost), State}; -+handle_call({get_user_messages_at, User, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ TName = messages_table(VHost, Date), -+ UName = users_table(VHost), -+ SName = servers_table(VHost), -+ RName = resources_table(VHost), -+ Query = ["SELECT users.username,", -+ "servers.server,", -+ "resources.resource,", -+ "messages.direction," -+ "messages.type," -+ "messages.subject," -+ "messages.body," -+ "messages.timestamp " -+ "FROM ",TName," AS messages " -+ "JOIN ",UName," AS users ON peer_name_id=user_id ", -+ "JOIN ",SName," AS servers ON peer_server_id=server_id ", -+ "JOIN ",RName," AS resources ON peer_resource_id=resource_id ", -+ "WHERE owner_id=\"",get_user_id(DBRef, VHost, User),"\" ", -+ "ORDER BY timestamp ASC;"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ Fun = fun([Peer_name, Peer_server, Peer_resource, -+ Direction, -+ Type, -+ Subject, Body, -+ Timestamp]) -> -+ #msg{peer_name=Peer_name, peer_server=Peer_server, peer_resource=Peer_resource, -+ direction=list_to_atom(Direction), -+ type=Type, -+ subject=Subject, body=Body, -+ timestamp=Timestamp} -+ end, -+ {ok, lists:map(Fun, Result)}; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_dates}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["SELECT at ", -+ "FROM ",SName," ", -+ "GROUP BY at ", -+ "ORDER BY DATE(at) DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ [ Date || [Date] <- Result ]; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_users_settings}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Query = ["SELECT username,dolog_default,dolog_list,donotlog_list ", -+ "FROM ",settings_table(VHost)," ", -+ "JOIN ",users_table(VHost)," ON user_id=owner_id;"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, lists:map(fun([Owner, DoLogDef, DoLogL, DoNotLogL]) -> -+ #user_settings{owner_name=Owner, -+ dolog_default=list_to_bool(DoLogDef), -+ dolog_list=string_to_list(DoLogL), -+ donotlog_list=string_to_list(DoNotLogL) -+ } -+ end, Result)}; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({get_user_settings, User}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Query = ["SELECT dolog_default,dolog_list,donotlog_list FROM ",settings_table(VHost)," ", -+ "WHERE owner_id=\"",get_user_id(DBRef, VHost, User),"\";"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, []} -> -+ {ok, []}; -+ {data, [[Owner, DoLogDef, DoLogL, DoNotLogL]]} -> -+ {ok, #user_settings{owner_name=Owner, -+ dolog_default=list_to_bool(DoLogDef), -+ dolog_list=string_to_list(DoLogL), -+ donotlog_list=string_to_list(DoNotLogL)}}; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({set_user_settings, User, #user_settings{dolog_default=DoLogDef, -+ dolog_list=DoLogL, -+ donotlog_list=DoNotLogL}}, -+ _From, #state{dbref=DBRef, vhost=VHost} = State) -> -+ User_id = get_user_id(DBRef, VHost, User), -+ -+ Query = ["UPDATE ",settings_table(VHost)," ", -+ "SET dolog_default=",bool_to_list(DoLogDef),", ", -+ "dolog_list='",list_to_string(DoLogL),"', ", -+ "donotlog_list='",list_to_string(DoNotLogL),"' ", -+ "WHERE owner_id=\"",User_id,"\";"], -+ -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {updated, 0} -> -+ IQuery = ["INSERT INTO ",settings_table(VHost)," ", -+ "(owner_id, dolog_default, dolog_list, donotlog_list) ", -+ "VALUES ", -+ "('",User_id,"', ",bool_to_list(DoLogDef),",'",list_to_string(DoLogL),"','",list_to_string(DoNotLogL),"');"], -+ case sql_query_internal_silent(DBRef, IQuery) of -+ {updated, _} -> -+ ?MYDEBUG("New settings for ~s@~s", [User, VHost]), -+ ok; -+ {error, Reason} -> -+ case regexp:match(Reason, "#23000") of -+ % Already exists -+ {match, _, _} -> -+ ok; -+ _ -> -+ ?ERROR_MSG("Failed setup user ~p@~p: ~p", [User, VHost, Reason]), -+ error -+ end -+ end; -+ {updated, 1} -> -+ ?MYDEBUG("Updated settings for ~s@~s", [User, VHost]), -+ ok; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({stop}, _From, #state{vhost=VHost}=State) -> -+ ets:delete(ets_users_table(VHost)), -+ ets:delete(ets_servers_table(VHost)), -+ ?MYDEBUG("Stoping mysql backend for ~p", [VHost]), -+ {stop, normal, ok, State}; -+handle_call(Msg, _From, State) -> -+ ?INFO_MSG("Got call Msg: ~p, State: ~p", [Msg, State]), -+ {noreply, State}. -+ -+handle_cast({rebuild_stats}, State) -> -+ rebuild_all_stats_int(State), -+ {noreply, State}; -+handle_cast({drop_user, User}, #state{vhost=VHost} = State) -> -+ Fun = fun() -> -+ {ok, DBRef} = open_mysql_connection(State), -+ {ok, Dates} = get_user_stats_int(DBRef, User, VHost), -+ MDResult = lists:map(fun({Date, _}) -> -+ delete_all_messages_by_user_at_int(DBRef, User, VHost, Date) -+ end, Dates), -+ StDResult = delete_all_stats_by_user_int(DBRef, User, VHost), -+ SDResult = delete_user_settings_int(DBRef, User, VHost), -+ case lists:all(fun(Result) when Result == ok -> -+ true; -+ (Result) when Result == error -> -+ false -+ end, lists:append([MDResult, [StDResult], [SDResult]])) of -+ true -> -+ ?INFO_MSG("Removed ~s@~s", [User, VHost]); -+ false -> -+ ?ERROR_MSG("Failed to remove ~s@~s", [User, VHost]) -+ end, -+ close_mysql_connection(DBRef) -+ end, -+ spawn(Fun), -+ {noreply, State}; -+handle_cast(Msg, State) -> -+ ?INFO_MSG("Got cast Msg:~p, State:~p", [Msg, State]), -+ {noreply, State}. -+ -+handle_info(clear_ets_tables, State) -> -+ ets:delete_all_objects(ets_users_table(State#state.vhost)), -+ ets:delete_all_objects(ets_resources_table(State#state.vhost)), -+ {noreply, State}; -+handle_info({'DOWN', _MonitorRef, process, _Pid, _Info}, State) -> -+ {stop, connection_dropped, State}; -+handle_info(Info, State) -> -+ ?INFO_MSG("Got Info:~p, State:~p", [Info, State]), -+ {noreply, State}. -+ -+terminate(_Reason, #state{dbref=DBRef}=_State) -> -+ close_mysql_connection(DBRef), -+ ok. -+ -+code_change(_OldVsn, State, _Extra) -> -+ {ok, State}. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+log_message(VHost, Msg) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {log_message, Msg}, ?CALL_TIMEOUT). -+rebuild_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {rebuild_stats}). -+rebuild_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {rebuild_stats_at, Date}, ?CALL_TIMEOUT). -+delete_messages_by_user_at(VHost, Msgs, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_by_user_at, Msgs, Date}, ?CALL_TIMEOUT). -+delete_all_messages_by_user_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_all_messages_by_user_at, User, Date}, ?CALL_TIMEOUT). -+delete_messages_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_at, Date}, ?CALL_TIMEOUT). -+get_vhost_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats}, ?CALL_TIMEOUT). -+get_vhost_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats_at, Date}, ?CALL_TIMEOUT). -+get_user_stats(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_stats, User}, ?CALL_TIMEOUT). -+get_user_messages_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_messages_at, User, Date}, ?CALL_TIMEOUT). -+get_dates(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_dates}, ?CALL_TIMEOUT). -+get_users_settings(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_users_settings}, ?CALL_TIMEOUT). -+get_user_settings(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_settings, User}, ?CALL_TIMEOUT). -+set_user_settings(User, VHost, Set) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {set_user_settings, User, Set}, ?CALL_TIMEOUT). -+drop_user(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {drop_user, User}). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+increment_user_stats(DBRef, User_name, User_id, VHost, PNameID, PServerID, Date) -> -+ SName = stats_table(VHost), -+ UQuery = ["UPDATE ",SName," ", -+ "SET count=count+1 ", -+ "WHERE owner_id=\"",User_id,"\" AND peer_name_id=\"",PNameID,"\" AND peer_server_id=\"",PServerID,"\" AND at=\"",Date,"\";"], -+ -+ case sql_query_internal(DBRef, UQuery) of -+ {updated, 0} -> -+ IQuery = ["INSERT INTO ",SName," ", -+ "(owner_id, peer_name_id, peer_server_id, at, count) ", -+ "VALUES ", -+ "('",User_id,"', '",PNameID,"', '",PServerID,"', '",Date,"', '1');"], -+ case sql_query_internal(DBRef, IQuery) of -+ {updated, _} -> -+ ?MYDEBUG("New stats for ~s@~s at ~s", [User_name, VHost, Date]), -+ ok; -+ {error, _} -> -+ error -+ end; -+ {updated, _} -> -+ ?MYDEBUG("Updated stats for ~s@~s at ~s", [User_name, VHost, Date]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+get_dates_int(DBRef, VHost) -> -+ case sql_query_internal(DBRef, ["SHOW TABLES"]) of -+ {data, Tables} -> -+ lists:foldl(fun([Table], Dates) -> -+ Reg = lists:sublist(prefix(),2,length(prefix())) ++ ".*" ++ escape_vhost(VHost), -+ case regexp:match(Table, Reg) of -+ {match, 1, _} -> -+ ?MYDEBUG("matched ~p against ~p", [Table, Reg]), -+ case regexp:match(Table,"[0-9]+-[0-9]+-[0-9]+") of -+ {match, S, E} -> -+ lists:append(Dates, [lists:sublist(Table,S,E)]); -+ nomatch -> -+ Dates -+ end; -+ -+ _ -> -+ Dates -+ end -+ end, [], Tables); -+ {error, _} -> -+ [] -+ end. -+ -+rebuild_all_stats_int(#state{vhost=VHost}=State) -> -+ Fun = fun() -> -+ {ok, DBRef} = open_mysql_connection(State), -+ ok = delete_nonexistent_stats(DBRef, VHost), -+ case lists:filter(fun(Date) -> -+ case catch rebuild_stats_at_int(DBRef, VHost, Date) of -+ ok -> false; -+ error -> true; -+ {'EXIT', _} -> true -+ end -+ end, get_dates_int(DBRef, VHost)) of -+ [] -> ok; -+ FTables -> -+ ?ERROR_MSG("Failed to rebuild stats for ~p dates", [FTables]), -+ error -+ end, -+ close_mysql_connection(DBRef) -+ end, -+ spawn(Fun). -+ -+rebuild_stats_at_int(DBRef, VHost, Date) -> -+ TempTable = temp_table(VHost), -+ Fun = fun() -> -+ Table = messages_table(VHost, Date), -+ STable = stats_table(VHost), -+ -+ DQuery = [ "DELETE FROM ",STable," ", -+ "WHERE at='",Date,"';"], -+ -+ ok = create_temp_table(DBRef, TempTable), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",Table," WRITE, ",TempTable," WRITE;"]), -+ SQuery = ["INSERT INTO ",TempTable," ", -+ "(owner_id,peer_name_id,peer_server_id,at,count) ", -+ "SELECT owner_id,peer_name_id,peer_server_id,\"",Date,"\",count(*) ", -+ "FROM ",Table," GROUP BY owner_id,peer_name_id,peer_server_id;"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, 0} -> -+ Count = sql_query_internal(DBRef, ["SELECT count(*) FROM ",Table,";"]), -+ case Count of -+ {data, [["0"]]} -> -+ {updated, _} = sql_query_internal(DBRef, ["DROP TABLE ",Table,";"]), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",STable," WRITE;"]), -+ {updated, _} = sql_query_internal(DBRef, DQuery), -+ ok; -+ _ -> -+ ?ERROR_MSG("Failed to calculate stats for ~s table! Count was ~p.", [Date, Count]), -+ error -+ end; -+ {updated, _} -> -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",STable," WRITE, ",TempTable," WRITE;"]), -+ {updated, _} = sql_query_internal(DBRef, DQuery), -+ SQuery1 = ["INSERT INTO ",STable," ", -+ "(owner_id,peer_name_id,peer_server_id,at,count) ", -+ "SELECT owner_id,peer_name_id,peer_server_id,at,count ", -+ "FROM ",TempTable,";"], -+ case sql_query_internal(DBRef, SQuery1) of -+ {updated, _} -> ok; -+ {error, _} -> error -+ end; -+ {error, _} -> error -+ end -+ end, -+ -+ case catch apply(Fun, []) of -+ ok -> -+ ?INFO_MSG("Rebuilded stats for ~p at ~p", [VHost, Date]), -+ ok; -+ error -> -+ error; -+ {'EXIT', Reason} -> -+ ?ERROR_MSG("Failed to rebuild stats for ~s table: ~p.", [Date, Reason]), -+ error -+ end, -+ sql_query_internal(DBRef, ["UNLOCK TABLES;"]), -+ sql_query_internal(DBRef, ["DROP TABLE ",TempTable,";"]), -+ ok. -+ -+ -+delete_nonexistent_stats(DBRef, VHost) -> -+ Dates = get_dates_int(DBRef, VHost), -+ STable = stats_table(VHost), -+ -+ Temp = lists:flatmap(fun(Date) -> -+ ["\"",Date,"\"",","] -+ end, Dates), -+ -+ case Temp of -+ [] -> -+ ok; -+ _ -> -+ % replace last "," with ");" -+ Temp1 = lists:append([lists:sublist(Temp, length(Temp)-1), ");"]), -+ Query = ["DELETE FROM ",STable," ", -+ "WHERE at NOT IN (", Temp1], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ok; -+ {error, _} -> -+ error -+ end -+ end. -+ -+get_user_stats_int(DBRef, User, VHost) -> -+ SName = stats_table(VHost), -+ Query = ["SELECT at, sum(count) as allcount ", -+ "FROM ",SName," ", -+ "WHERE owner_id=\"",get_user_id(DBRef, VHost, User),"\" ", -+ "GROUP BY at " -+ "ORDER BY DATE(at) DESC;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, [ {Date, list_to_integer(Count)} || [Date, Count] <- Result]}; -+ {error, Result} -> -+ {error, Result} -+ end. -+ -+delete_all_messages_by_user_at_int(DBRef, User, VHost, Date) -> -+ DQuery = ["DELETE FROM ",messages_table(VHost, Date)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\");"], -+ case sql_query_internal(DBRef, DQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped messages for ~s@~s at ~s", [User, VHost, Date]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+delete_all_stats_by_user_int(DBRef, User, VHost) -> -+ SQuery = ["DELETE FROM ",stats_table(VHost)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\");"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped all stats for ~s@~s", [User, VHost]), -+ ok; -+ {error, _} -> error -+ end. -+ -+delete_stats_by_user_at_int(DBRef, User, VHost, Date) -> -+ SQuery = ["DELETE FROM ",stats_table(VHost)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\") ", -+ "AND at=\"",Date,"\";"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped stats for ~s@~s at ~s", [User, VHost, Date]), -+ ok; -+ {error, _} -> error -+ end. -+ -+delete_user_settings_int(DBRef, User, VHost) -> -+ Query = ["DELETE FROM ",settings_table(VHost)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\");"], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped ~s@~s settings", [User, VHost]), -+ ok; -+ {error, Reason} -> -+ ?ERROR_MSG("Failed to drop ~s@~s settings: ~p", [User, VHost, Reason]), -+ error -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% tables internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+create_temp_table(DBRef, Name) -> -+ Query = ["CREATE TABLE ",Name," (", -+ "owner_id MEDIUMINT UNSIGNED, ", -+ "peer_name_id MEDIUMINT UNSIGNED, ", -+ "peer_server_id MEDIUMINT UNSIGNED, ", -+ "at VARCHAR(11), ", -+ "count INT(11) ", -+ ") ENGINE=MyISAM CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> ok; -+ {error, _Reason} -> error -+ end. -+ -+create_stats_table(#state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["CREATE TABLE ",SName," (", -+ "owner_id MEDIUMINT UNSIGNED, ", -+ "peer_name_id MEDIUMINT UNSIGNED, ", -+ "peer_server_id MEDIUMINT UNSIGNED, ", -+ "at varchar(20), ", -+ "count int(11), ", -+ "INDEX(owner_id, peer_name_id, peer_server_id), ", -+ "INDEX(at)" -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ ?INFO_MSG("Created stats table for ~p", [VHost]), -+ rebuild_all_stats_int(State), -+ ok; -+ {error, Reason} -> -+ case regexp:match(Reason, "#42S01") of -+ {match, _, _} -> -+ ?MYDEBUG("Stats table for ~p already exists", [VHost]), -+ CheckQuery = ["SHOW COLUMNS FROM ",SName," LIKE 'peer_%_id';"], -+ case sql_query_internal(DBRef, CheckQuery) of -+ {data, Elems} when length(Elems) == 2 -> -+ ?MYDEBUG("Stats table structure is ok", []), -+ ok; -+ _ -> -+ ?INFO_MSG("It seems like stats table structure is invalid. I will drop it and recreate", []), -+ case sql_query_internal(DBRef, ["DROP TABLE ",SName,";"]) of -+ {updated, _} -> -+ ?INFO_MSG("Successfully dropped ~p", [SName]); -+ _ -> -+ ?ERROR_MSG("Failed to drop ~p. You should drop it and restart module", [SName]) -+ end, -+ error -+ end; -+ _ -> -+ ?ERROR_MSG("Failed to create stats table for ~p: ~p", [VHost, Reason]), -+ error -+ end -+ end. -+ -+create_settings_table(#state{dbref=DBRef, vhost=VHost}) -> -+ SName = settings_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",SName," (", -+ "owner_id MEDIUMINT UNSIGNED PRIMARY KEY, ", -+ "dolog_default TINYINT(1) NOT NULL DEFAULT 1, ", -+ "dolog_list TEXT, ", -+ "donotlog_list TEXT ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created settings table for ~p", [VHost]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_users_table(#state{dbref=DBRef, vhost=VHost}) -> -+ SName = users_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",SName," (", -+ "username TEXT NOT NULL, ", -+ "user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, ", -+ "UNIQUE INDEX(username(",?INDEX_SIZE,")) ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created users table for ~p", [VHost]), -+ ets:new(ets_users_table(VHost), [named_table, set, public]), -+ %update_users_from_db(DBRef, VHost), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_servers_table(#state{dbref=DBRef, vhost=VHost}) -> -+ SName = servers_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",SName," (", -+ "server TEXT NOT NULL, ", -+ "server_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, ", -+ "UNIQUE INDEX(server(",?INDEX_SIZE,")) ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created servers table for ~p", [VHost]), -+ ets:new(ets_servers_table(VHost), [named_table, set, public]), -+ update_servers_from_db(DBRef, VHost), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_resources_table(#state{dbref=DBRef, vhost=VHost}) -> -+ RName = resources_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",RName," (", -+ "resource TEXT NOT NULL, ", -+ "resource_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, ", -+ "UNIQUE INDEX(resource(",?INDEX_SIZE,")) ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created resources table for ~p", [VHost]), -+ ets:new(ets_resources_table(VHost), [named_table, set, public]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_msg_table(DBRef, VHost, Date) -> -+ TName = messages_table(VHost, Date), -+ Query = ["CREATE TABLE ",TName," (", -+ "owner_id MEDIUMINT UNSIGNED, ", -+ "peer_name_id MEDIUMINT UNSIGNED, ", -+ "peer_server_id MEDIUMINT UNSIGNED, ", -+ "peer_resource_id MEDIUMINT(8) UNSIGNED, ", -+ "direction ENUM('to', 'from'), ", -+ "type ENUM('chat','error','groupchat','headline','normal') NOT NULL, ", -+ "subject TEXT, ", -+ "body TEXT, ", -+ "timestamp DOUBLE, ", -+ "INDEX search_i (owner_id, peer_name_id, peer_server_id, peer_resource_id), ", -+ "FULLTEXT (body) " -+ ") ENGINE=MyISAM CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _MySQLRes} -> -+ ?MYDEBUG("Created msg table for ~p at ~p", [VHost, Date]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% internal ets cache (users, servers, resources) -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+update_servers_from_db(DBRef, VHost) -> -+ ?INFO_MSG("Reading servers from db for ~p", [VHost]), -+ SQuery = ["SELECT server, server_id FROM ",servers_table(VHost),";"], -+ {data, Result} = sql_query_internal(DBRef, SQuery), -+ true = ets:delete_all_objects(ets_servers_table(VHost)), -+ true = ets:insert(ets_servers_table(VHost), [ {Server, Server_id} || [Server, Server_id] <- Result]). -+ -+%update_users_from_db(DBRef, VHost) -> -+% ?INFO_MSG("Reading users from db for ~p", [VHost]), -+% SQuery = ["SELECT username, user_id FROM ",users_table(VHost),";"], -+% {data, Result} = sql_query_internal(DBRef, SQuery), -+% true = ets:delete_all_objects(ets_users_table(VHost)), -+% true = ets:insert(ets_users_table(VHost), [ {Username, User_id} || [Username, User_id] <- Result]). -+ -+%get_user_name(DBRef, VHost, User_id) -> -+% case ets:match(ets_users_table(VHost), {'$1', User_id}) of -+% [[User]] -> User; -+% % this can be in clustered environment -+% [] -> -+% %update_users_from_db(DBRef, VHost), -+% SQuery = ["SELECT username FROM ",users_table(VHost)," ", -+% "WHERE user_id=\"",User_id,"\";"], -+% {data, [[Name]]} = sql_query_internal(DBRef, SQuery), -+% % cache {user, id} pair -+% ets:insert(ets_users_table(VHost), {Name, User_id}), -+% Name -+% end. -+ -+%get_server_name(DBRef, VHost, Server_id) -> -+% case ets:match(ets_servers_table(VHost), {'$1', Server_id}) of -+% [[Server]] -> Server; -+ % this can be in clustered environment -+% [] -> -+% update_servers_from_db(DBRef, VHost), -+% [[Server1]] = ets:match(ets_servers_table(VHost), {'$1', Server_id}), -+% Server1 -+% end. -+ -+get_user_id_from_db(DBRef, VHost, User) -> -+ SQuery = ["SELECT user_id FROM ",users_table(VHost)," ", -+ "WHERE username=\"",User,"\";"], -+ case sql_query_internal(DBRef, SQuery) of -+ % no such user in db -+ {data, []} -> -+ {ok, []}; -+ {data, [[DBId]]} -> -+ % cache {user, id} pair -+ ets:insert(ets_users_table(VHost), {User, DBId}), -+ {ok, DBId} -+ end. -+get_user_id(DBRef, VHost, User) -> -+ % Look at ets -+ case ets:match(ets_users_table(VHost), {User, '$1'}) of -+ [] -> -+ % Look at db -+ case get_user_id_from_db(DBRef, VHost, User) of -+ % no such user in db -+ {ok, []} -> -+ IQuery = ["INSERT INTO ",users_table(VHost)," ", -+ "SET username=\"",User,"\";"], -+ case sql_query_internal_silent(DBRef, IQuery) of -+ {updated, _} -> -+ {ok, NewId} = get_user_id_from_db(DBRef, VHost, User), -+ NewId; -+ {error, Reason} -> -+ % this can be in clustered environment -+ {match, _, _} = regexp:match(Reason, "#23000"), -+ ?ERROR_MSG("Duplicate key name for ~p", [User]), -+ {ok, ClID} = get_user_id_from_db(DBRef, VHost, User), -+ ClID -+ end; -+ {ok, DBId} -> -+ DBId -+ end; -+ [[EtsId]] -> EtsId -+ end. -+ -+get_server_id(DBRef, VHost, Server) -> -+ case ets:match(ets_servers_table(VHost), {Server, '$1'}) of -+ [] -> -+ IQuery = ["INSERT INTO ",servers_table(VHost)," ", -+ "SET server=\"",Server,"\";"], -+ case sql_query_internal_silent(DBRef, IQuery) of -+ {updated, _} -> -+ SQuery = ["SELECT server_id FROM ",servers_table(VHost)," ", -+ "WHERE server=\"",Server,"\";"], -+ {data, [[Id]]} = sql_query_internal(DBRef, SQuery), -+ ets:insert(ets_servers_table(VHost), {Server, Id}), -+ Id; -+ {error, Reason} -> -+ % this can be in clustered environment -+ {match, _, _} = regexp:match(Reason, "#23000"), -+ ?ERROR_MSG("Duplicate key name for ~p", [Server]), -+ update_servers_from_db(DBRef, VHost), -+ [[Id1]] = ets:match(ets_servers_table(VHost), {Server, '$1'}), -+ Id1 -+ end; -+ [[Id]] -> Id -+ end. -+ -+get_resource_id_from_db(DBRef, VHost, Resource) -> -+ SQuery = ["SELECT resource_id FROM ",resources_table(VHost)," ", -+ "WHERE resource=\"",ejabberd_odbc:escape(Resource),"\";"], -+ case sql_query_internal(DBRef, SQuery) of -+ % no such resource in db -+ {data, []} -> -+ {ok, []}; -+ {data, [[DBId]]} -> -+ % cache {resource, id} pair -+ ets:insert(ets_resources_table(VHost), {Resource, DBId}), -+ {ok, DBId} -+ end. -+get_resource_id(DBRef, VHost, Resource) -> -+ % Look at ets -+ case ets:match(ets_resources_table(VHost), {Resource, '$1'}) of -+ [] -> -+ % Look at db -+ case get_resource_id_from_db(DBRef, VHost, Resource) of -+ % no such resource in db -+ {ok, []} -> -+ IQuery = ["INSERT INTO ",resources_table(VHost)," ", -+ "SET resource=\"",ejabberd_odbc:escape(Resource),"\";"], -+ case sql_query_internal_silent(DBRef, IQuery) of -+ {updated, _} -> -+ {ok, NewId} = get_resource_id_from_db(DBRef, VHost, Resource), -+ NewId; -+ {error, Reason} -> -+ % this can be in clustered environment -+ {match, _, _} = regexp:match(Reason, "#23000"), -+ ?ERROR_MSG("Duplicate key name for ~p", [Resource]), -+ {ok, ClID} = get_resource_id_from_db(DBRef, VHost, Resource), -+ ClID -+ end; -+ {ok, DBId} -> -+ DBId -+ end; -+ [[EtsId]] -> EtsId -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% SQL internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+sql_query_internal(DBRef, Query) -> -+ case sql_query_internal_silent(DBRef, Query) of -+ {error, Reason} -> -+ ?ERROR_MSG("~p while ~p", [Reason, lists:append(Query)]), -+ {error, Reason}; -+ Rez -> Rez -+ end. -+ -+sql_query_internal_silent(DBRef, Query) -> -+ ?MYDEBUG("DOING: \"~s\"", [lists:append(Query)]), -+ get_result(mysql_conn:fetch(DBRef, Query, self(), ?MYSQL_TIMEOUT)). -+ -+get_result({updated, MySQLRes}) -> -+ {updated, mysql:get_result_affected_rows(MySQLRes)}; -+get_result({data, MySQLRes}) -> -+ {data, mysql:get_result_rows(MySQLRes)}; -+get_result({error, "query timed out"}) -> -+ {error, "query timed out"}; -+get_result({error, MySQLRes}) -> -+ Reason = mysql:get_result_reason(MySQLRes), -+ {error, Reason}. ---- mod_logdb_mysql5.erl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ mod_logdb_mysql5.erl 2009-02-05 19:20:14.000000000 +0200 -@@ -0,0 +1,978 @@ -+%%%---------------------------------------------------------------------- -+%%% File : mod_logdb_mysql5.erl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : MySQL 5 backend for mod_logdb -+%%% Version : trunk -+%%% Id : $Id: mod_logdb_mysql5.erl 1253 2009-02-02 11:10:03Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-module(mod_logdb_mysql5). -+-author('o.palij@gmail.com'). -+ -+-include("mod_logdb.hrl"). -+-include("ejabberd.hrl"). -+-include("jlib.hrl"). -+ -+-behaviour(gen_logdb). -+-behaviour(gen_server). -+ -+% gen_server -+-export([code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2]). -+% gen_mod -+-export([start/2, stop/1]). -+% gen_logdb -+-export([log_message/2, -+ rebuild_stats/1, -+ rebuild_stats_at/2, -+ delete_messages_by_user_at/3, delete_all_messages_by_user_at/3, delete_messages_at/2, -+ get_vhost_stats/1, get_vhost_stats_at/2, get_user_stats/2, get_user_messages_at/3, -+ get_dates/1, -+ get_users_settings/1, get_user_settings/2, set_user_settings/3, -+ drop_user/2]). -+ -+% gen_server call timeout -+-define(CALL_TIMEOUT, 30000). -+-define(MYSQL_TIMEOUT, 60000). -+-define(INDEX_SIZE, integer_to_list(170)). -+-define(PROCNAME, mod_logdb_mysql5). -+ -+-import(mod_logdb, [list_to_bool/1, bool_to_list/1, -+ list_to_string/1, string_to_list/1, -+ convert_timestamp_brief/1]). -+ -+-record(state, {dbref, vhost, server, port, db, user, password}). -+ -+% replace "." with "_" -+escape_vhost(VHost) -> lists:map(fun(46) -> 95; -+ (A) -> A -+ end, VHost). -+prefix() -> -+ "`logdb_". -+ -+suffix(VHost) -> -+ "_" ++ escape_vhost(VHost) ++ "`". -+ -+messages_table(VHost, Date) -> -+ prefix() ++ "messages_" ++ Date ++ suffix(VHost). -+ -+% TODO: this needs to be redone to unify view name in stored procedure and in delete_messages_at/2 -+view_table(VHost, Date) -> -+ Table = messages_table(VHost, Date), -+ TablewoQ = lists:sublist(Table, 2, length(Table) - 2), -+ lists:append(["`v_", TablewoQ, "`"]). -+ -+stats_table(VHost) -> -+ prefix() ++ "stats" ++ suffix(VHost). -+ -+temp_table(VHost) -> -+ prefix() ++ "temp" ++ suffix(VHost). -+ -+settings_table(VHost) -> -+ prefix() ++ "settings" ++ suffix(VHost). -+ -+users_table(VHost) -> -+ prefix() ++ "users" ++ suffix(VHost). -+servers_table(VHost) -> -+ prefix() ++ "servers" ++ suffix(VHost). -+resources_table(VHost) -> -+ prefix() ++ "resources" ++ suffix(VHost). -+ -+logmessage_name(VHost) -> -+ prefix() ++ "logmessage" ++ suffix(VHost). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_mod callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+start(VHost, Opts) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:start({local, Proc}, ?MODULE, [VHost, Opts], []). -+ -+stop(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {stop}, ?CALL_TIMEOUT). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_server callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+init([VHost, Opts]) -> -+ crypto:start(), -+ -+ Server = gen_mod:get_opt(server, Opts, "localhost"), -+ Port = gen_mod:get_opt(port, Opts, 3306), -+ DB = gen_mod:get_opt(db, Opts, "logdb"), -+ User = gen_mod:get_opt(user, Opts, "root"), -+ Password = gen_mod:get_opt(password, Opts, ""), -+ -+ St = #state{vhost=VHost, -+ server=Server, port=Port, db=DB, -+ user=User, password=Password}, -+ -+ case open_mysql_connection(St) of -+ {ok, DBRef} -> -+ State = St#state{dbref=DBRef}, -+ ok = create_internals(State), -+ ok = create_stats_table(State), -+ ok = create_settings_table(State), -+ ok = create_users_table(State), -+ ok = create_servers_table(State), -+ ok = create_resources_table(State), -+ erlang:monitor(process, DBRef), -+ {ok, State}; -+ {error, Reason} -> -+ ?ERROR_MSG("MySQL connection failed: ~p~n", [Reason]), -+ {stop, db_connection_failed} -+ end. -+ -+open_mysql_connection(#state{server=Server, port=Port, db=DB, -+ user=DBUser, password=Password} = _State) -> -+ LogFun = fun(debug, _Format, _Argument) -> -+ %?MYDEBUG(Format, Argument); -+ ok; -+ (error, Format, Argument) -> -+ ?ERROR_MSG(Format, Argument); -+ (Level, Format, Argument) -> -+ ?MYDEBUG("MySQL (~p)~n", [Level]), -+ ?MYDEBUG(Format, Argument) -+ end, -+ mysql_conn:start(Server, Port, DBUser, Password, DB, [65536, 131072], LogFun). -+ -+close_mysql_connection(DBRef) -> -+ ?MYDEBUG("Closing ~p mysql connection", [DBRef]), -+ mysql_conn:stop(DBRef). -+ -+handle_call({rebuild_stats_at, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Reply = rebuild_stats_at_int(DBRef, VHost, Date), -+ {reply, Reply, State}; -+handle_call({delete_messages_by_user_at, [], _Date}, _From, State) -> -+ {reply, error, State}; -+handle_call({delete_messages_by_user_at, Msgs, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Temp = lists:flatmap(fun(#msg{timestamp=Timestamp} = _Msg) -> -+ ["\"",Timestamp,"\"",","] -+ end, Msgs), -+ -+ Temp1 = lists:append([lists:sublist(Temp, length(Temp)-1), ");"]), -+ -+ Query = ["DELETE FROM ",messages_table(VHost, Date)," ", -+ "WHERE timestamp IN (", Temp1], -+ -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {updated, Aff} -> -+ ?MYDEBUG("Aff=~p", [Aff]), -+ rebuild_stats_at_int(DBRef, VHost, Date); -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({delete_all_messages_by_user_at, User, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ ok = delete_all_messages_by_user_at_int(DBRef, User, VHost, Date), -+ ok = delete_stats_by_user_at_int(DBRef, User, VHost, Date), -+ {reply, ok, State}; -+handle_call({delete_messages_at, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Fun = fun() -> -+ {updated, _} = sql_query_internal(DBRef, ["DROP TABLE ",messages_table(VHost, Date),";"]), -+ TQuery = ["DELETE FROM ",stats_table(VHost)," " -+ "WHERE at=\"",Date,"\";"], -+ {updated, _} = sql_query_internal(DBRef, TQuery), -+ VQuery = ["DROP VIEW IF EXISTS ",view_table(VHost,Date),";"], -+ {updated, _} = sql_query_internal(DBRef, VQuery), -+ ok -+ end, -+ Reply = -+ case catch apply(Fun, []) of -+ ok -> -+ ok; -+ {'EXIT', _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["SELECT at, sum(count) ", -+ "FROM ",SName," ", -+ "GROUP BY at ", -+ "ORDER BY DATE(at) DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, [ {Date, list_to_integer(Count)} || [Date, Count] <- Result ]}; -+ {error, Reason} -> -+ % TODO: Duplicate error message ? -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats_at, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["SELECT username, sum(count) as allcount ", -+ "FROM ",SName," ", -+ "JOIN ",users_table(VHost)," ON owner_id=user_id " -+ "WHERE at=\"",Date,"\" ", -+ "GROUP BY username ", -+ "ORDER BY allcount DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, [ {User, list_to_integer(Count)} || [User, Count] <- Result ]}; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_user_stats, User}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ {reply, get_user_stats_int(DBRef, User, VHost), State}; -+handle_call({get_user_messages_at, User, Date}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Query = ["SELECT peer_name,", -+ "peer_server,", -+ "peer_resource,", -+ "direction," -+ "type," -+ "subject," -+ "body," -+ "timestamp " -+ "FROM ",view_table(VHost, Date)," " -+ "WHERE owner_name=\"",User,"\";"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ Fun = fun([Peer_name, Peer_server, Peer_resource, -+ Direction, -+ Type, -+ Subject, Body, -+ Timestamp]) -> -+ #msg{peer_name=Peer_name, peer_server=Peer_server, peer_resource=Peer_resource, -+ direction=list_to_atom(Direction), -+ type=Type, -+ subject=Subject, body=Body, -+ timestamp=Timestamp} -+ end, -+ {ok, lists:map(Fun, Result)}; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_dates}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["SELECT at ", -+ "FROM ",SName," ", -+ "GROUP BY at ", -+ "ORDER BY DATE(at) DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ [ Date || [Date] <- Result ]; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_users_settings}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Query = ["SELECT username,dolog_default,dolog_list,donotlog_list ", -+ "FROM ",settings_table(VHost)," ", -+ "JOIN ",users_table(VHost)," ON user_id=owner_id;"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, lists:map(fun([Owner, DoLogDef, DoLogL, DoNotLogL]) -> -+ #user_settings{owner_name=Owner, -+ dolog_default=list_to_bool(DoLogDef), -+ dolog_list=string_to_list(DoLogL), -+ donotlog_list=string_to_list(DoNotLogL) -+ } -+ end, Result)}; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({get_user_settings, User}, _From, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Query = ["SELECT dolog_default,dolog_list,donotlog_list FROM ",settings_table(VHost)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\");"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, []} -> -+ {ok, []}; -+ {data, [[Owner, DoLogDef, DoLogL, DoNotLogL]]} -> -+ {ok, #user_settings{owner_name=Owner, -+ dolog_default=list_to_bool(DoLogDef), -+ dolog_list=string_to_list(DoLogL), -+ donotlog_list=string_to_list(DoNotLogL)}}; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({set_user_settings, User, #user_settings{dolog_default=DoLogDef, -+ dolog_list=DoLogL, -+ donotlog_list=DoNotLogL}}, -+ _From, #state{dbref=DBRef, vhost=VHost} = State) -> -+ User_id = get_user_id(DBRef, VHost, User), -+ Query = ["UPDATE ",settings_table(VHost)," ", -+ "SET dolog_default=",bool_to_list(DoLogDef),", ", -+ "dolog_list='",list_to_string(DoLogL),"', ", -+ "donotlog_list='",list_to_string(DoNotLogL),"' ", -+ "WHERE owner_id=",User_id,";"], -+ -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {updated, 0} -> -+ IQuery = ["INSERT INTO ",settings_table(VHost)," ", -+ "(owner_id, dolog_default, dolog_list, donotlog_list) ", -+ "VALUES ", -+ "(",User_id,",",bool_to_list(DoLogDef),",'",list_to_string(DoLogL),"','",list_to_string(DoNotLogL),"');"], -+ case sql_query_internal_silent(DBRef, IQuery) of -+ {updated, _} -> -+ ?MYDEBUG("New settings for ~s@~s", [User, VHost]), -+ ok; -+ {error, Reason} -> -+ case regexp:match(Reason, "#23000") of -+ % Already exists -+ {match, _, _} -> -+ ok; -+ _ -> -+ ?ERROR_MSG("Failed setup user ~p@~p: ~p", [User, VHost, Reason]), -+ error -+ end -+ end; -+ {updated, 1} -> -+ ?MYDEBUG("Updated settings for ~s@~s", [User, VHost]), -+ ok; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({stop}, _From, #state{vhost=VHost}=State) -> -+ ?MYDEBUG("Stoping mysql5 backend for ~p", [VHost]), -+ {stop, normal, ok, State}; -+handle_call(Msg, _From, State) -> -+ ?INFO_MSG("Got call Msg: ~p, State: ~p", [Msg, State]), -+ {noreply, State}. -+ -+handle_cast({log_message, Msg}, #state{dbref=DBRef, vhost=VHost}=State) -> -+ Fun = fun() -> -+ Date = convert_timestamp_brief(Msg#msg.timestamp), -+ TableName = messages_table(VHost, Date), -+ -+ Query = [ "CALL ",logmessage_name(VHost)," " -+ "('", TableName, "',", -+ "'", Date, "',", -+ "'", Msg#msg.owner_name, "',", -+ "'", Msg#msg.peer_name, "',", -+ "'", Msg#msg.peer_server, "',", -+ "'", ejabberd_odbc:escape(Msg#msg.peer_resource), "',", -+ "'", atom_to_list(Msg#msg.direction), "',", -+ "'", Msg#msg.type, "',", -+ "'", ejabberd_odbc:escape(Msg#msg.subject), "',", -+ "'", ejabberd_odbc:escape(Msg#msg.body), "',", -+ "'", Msg#msg.timestamp, "');"], -+ -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Logged ok for ~p, peer: ~p", [Msg#msg.owner_name++"@"++VHost, -+ Msg#msg.peer_name++"@"++Msg#msg.peer_server]), -+ ok; -+ {error, _Reason} -> -+ error -+ end -+ end, -+ spawn(Fun), -+ {noreply, State}; -+handle_cast({rebuild_stats}, State) -> -+ rebuild_all_stats_int(State), -+ {noreply, State}; -+handle_cast({drop_user, User}, #state{vhost=VHost} = State) -> -+ Fun = fun() -> -+ {ok, DBRef} = open_mysql_connection(State), -+ {ok, Dates} = get_user_stats_int(DBRef, User, VHost), -+ MDResult = lists:map(fun({Date, _}) -> -+ delete_all_messages_by_user_at_int(DBRef, User, VHost, Date) -+ end, Dates), -+ StDResult = delete_all_stats_by_user_int(DBRef, User, VHost), -+ SDResult = delete_user_settings_int(DBRef, User, VHost), -+ case lists:all(fun(Result) when Result == ok -> -+ true; -+ (Result) when Result == error -> -+ false -+ end, lists:append([MDResult, [StDResult], [SDResult]])) of -+ true -> -+ ?INFO_MSG("Removed ~s@~s", [User, VHost]); -+ false -> -+ ?ERROR_MSG("Failed to remove ~s@~s", [User, VHost]) -+ end, -+ close_mysql_connection(DBRef) -+ end, -+ spawn(Fun), -+ {noreply, State}; -+handle_cast(Msg, State) -> -+ ?INFO_MSG("Got cast Msg:~p, State:~p", [Msg, State]), -+ {noreply, State}. -+ -+handle_info({'DOWN', _MonitorRef, process, _Pid, _Info}, State) -> -+ {stop, connection_dropped, State}; -+handle_info(Info, State) -> -+ ?INFO_MSG("Got Info:~p, State:~p", [Info, State]), -+ {noreply, State}. -+ -+terminate(_Reason, #state{dbref=DBRef}=_State) -> -+ close_mysql_connection(DBRef), -+ ok. -+ -+code_change(_OldVsn, State, _Extra) -> -+ {ok, State}. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+log_message(VHost, Msg) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {log_message, Msg}). -+rebuild_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {rebuild_stats}). -+rebuild_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {rebuild_stats_at, Date}, ?CALL_TIMEOUT). -+delete_messages_by_user_at(VHost, Msgs, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_by_user_at, Msgs, Date}, ?CALL_TIMEOUT). -+delete_all_messages_by_user_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_all_messages_by_user_at, User, Date}, ?CALL_TIMEOUT). -+delete_messages_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_at, Date}, ?CALL_TIMEOUT). -+get_vhost_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats}, ?CALL_TIMEOUT). -+get_vhost_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats_at, Date}, ?CALL_TIMEOUT). -+get_user_stats(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_stats, User}, ?CALL_TIMEOUT). -+get_user_messages_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_messages_at, User, Date}, ?CALL_TIMEOUT). -+get_dates(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_dates}, ?CALL_TIMEOUT). -+get_users_settings(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_users_settings}, ?CALL_TIMEOUT). -+get_user_settings(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_settings, User}, ?CALL_TIMEOUT). -+set_user_settings(User, VHost, Set) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {set_user_settings, User, Set}, ?CALL_TIMEOUT). -+drop_user(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {drop_user, User}). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+get_dates_int(DBRef, VHost) -> -+ case sql_query_internal(DBRef, ["SHOW TABLES"]) of -+ {data, Tables} -> -+ lists:foldl(fun([Table], Dates) -> -+ Reg = lists:sublist(prefix(),2,length(prefix())) ++ ".*" ++ escape_vhost(VHost), -+ case regexp:match(Table, Reg) of -+ {match, 1, _} -> -+ case regexp:match(Table,"[0-9]+-[0-9]+-[0-9]+") of -+ {match, S, E} -> -+ lists:append(Dates, [lists:sublist(Table,S,E)]); -+ nomatch -> -+ Dates -+ end; -+ _ -> -+ Dates -+ end -+ end, [], Tables); -+ {error, _} -> -+ [] -+ end. -+ -+rebuild_all_stats_int(#state{vhost=VHost}=State) -> -+ Fun = fun() -> -+ {ok, DBRef} = open_mysql_connection(State), -+ ok = delete_nonexistent_stats(DBRef, VHost), -+ case lists:filter(fun(Date) -> -+ case catch rebuild_stats_at_int(DBRef, VHost, Date) of -+ ok -> false; -+ error -> true; -+ {'EXIT', _} -> true -+ end -+ end, get_dates_int(DBRef, VHost)) of -+ [] -> ok; -+ FTables -> -+ ?ERROR_MSG("Failed to rebuild stats for ~p dates", [FTables]), -+ error -+ end, -+ close_mysql_connection(DBRef) -+ end, -+ spawn(Fun). -+ -+rebuild_stats_at_int(DBRef, VHost, Date) -> -+ TempTable = temp_table(VHost), -+ Fun = fun() -> -+ Table = messages_table(VHost, Date), -+ STable = stats_table(VHost), -+ -+ DQuery = [ "DELETE FROM ",STable," ", -+ "WHERE at='",Date,"';"], -+ -+ ok = create_temp_table(DBRef, TempTable), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",Table," WRITE, ",TempTable," WRITE;"]), -+ SQuery = ["INSERT INTO ",TempTable," ", -+ "(owner_id,peer_name_id,peer_server_id,at,count) ", -+ "SELECT owner_id,peer_name_id,peer_server_id,\"",Date,"\",count(*) ", -+ "FROM ",Table," WHERE ext is NULL GROUP BY owner_id,peer_name_id,peer_server_id;"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, 0} -> -+ Count = sql_query_internal(DBRef, ["SELECT count(*) FROM ",Table,";"]), -+ case Count of -+ {data, [["0"]]} -> -+ {updated, _} = sql_query_internal(DBRef, ["DROP VIEW IF EXISTS ",view_table(VHost,Date),";"]), -+ {updated, _} = sql_query_internal(DBRef, ["DROP TABLE ",Table,";"]), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",STable," WRITE;"]), -+ {updated, _} = sql_query_internal(DBRef, DQuery), -+ ok; -+ _ -> -+ ?ERROR_MSG("Failed to calculate stats for ~s table! Count was ~p.", [Date, Count]), -+ error -+ end; -+ {updated, _} -> -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",STable," WRITE, ",TempTable," WRITE;"]), -+ {updated, _} = sql_query_internal(DBRef, DQuery), -+ SQuery1 = ["INSERT INTO ",STable," ", -+ "(owner_id,peer_name_id,peer_server_id,at,count) ", -+ "SELECT owner_id,peer_name_id,peer_server_id,at,count ", -+ "FROM ",TempTable,";"], -+ case sql_query_internal(DBRef, SQuery1) of -+ {updated, _} -> ok; -+ {error, _} -> error -+ end; -+ {error, _} -> error -+ end -+ end, -+ -+ case catch apply(Fun, []) of -+ ok -> -+ ?INFO_MSG("Rebuilded stats for ~p at ~p", [VHost, Date]), -+ ok; -+ error -> -+ error; -+ {'EXIT', Reason} -> -+ ?ERROR_MSG("Failed to rebuild stats for ~s table: ~p.", [Date, Reason]), -+ error -+ end, -+ sql_query_internal(DBRef, ["UNLOCK TABLES;"]), -+ sql_query_internal(DBRef, ["DROP TABLE ",TempTable,";"]), -+ ok. -+ -+delete_nonexistent_stats(DBRef, VHost) -> -+ Dates = get_dates_int(DBRef, VHost), -+ STable = stats_table(VHost), -+ -+ Temp = lists:flatmap(fun(Date) -> -+ ["\"",Date,"\"",","] -+ end, Dates), -+ case Temp of -+ [] -> -+ ok; -+ _ -> -+ % replace last "," with ");" -+ Temp1 = lists:append([lists:sublist(Temp, length(Temp)-1), ");"]), -+ Query = ["DELETE FROM ",STable," ", -+ "WHERE at NOT IN (", Temp1], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ok; -+ {error, _} -> -+ error -+ end -+ end. -+ -+get_user_stats_int(DBRef, User, VHost) -> -+ SName = stats_table(VHost), -+ UName = users_table(VHost), -+ Query = ["SELECT stats.at, sum(stats.count) ", -+ "FROM ",UName," AS users ", -+ "JOIN ",SName," AS stats ON owner_id=user_id " -+ "WHERE users.username=\"",User,"\" ", -+ "GROUP BY stats.at " -+ "ORDER BY DATE(stats.at) DESC;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ {ok, [ {Date, list_to_integer(Count)} || [Date, Count] <- Result ]}; -+ {error, Result} -> -+ {error, Result} -+ end. -+ -+delete_all_messages_by_user_at_int(DBRef, User, VHost, Date) -> -+ DQuery = ["DELETE FROM ",messages_table(VHost, Date)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\");"], -+ case sql_query_internal(DBRef, DQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped messages for ~s@~s at ~s", [User, VHost, Date]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+delete_all_stats_by_user_int(DBRef, User, VHost) -> -+ SQuery = ["DELETE FROM ",stats_table(VHost)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\");"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped all stats for ~s@~s", [User, VHost]), -+ ok; -+ {error, _} -> error -+ end. -+ -+delete_stats_by_user_at_int(DBRef, User, VHost, Date) -> -+ SQuery = ["DELETE FROM ",stats_table(VHost)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\") ", -+ "AND at=\"",Date,"\";"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped stats for ~s@~s at ~s", [User, VHost, Date]), -+ ok; -+ {error, _} -> error -+ end. -+ -+delete_user_settings_int(DBRef, User, VHost) -> -+ Query = ["DELETE FROM ",settings_table(VHost)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost)," WHERE username=\"",User,"\");"], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped ~s@~s settings", [User, VHost]), -+ ok; -+ {error, Reason} -> -+ ?ERROR_MSG("Failed to drop ~s@~s settings: ~p", [User, VHost, Reason]), -+ error -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% tables internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+create_temp_table(DBRef, Name) -> -+ Query = ["CREATE TABLE ",Name," (", -+ "owner_id MEDIUMINT UNSIGNED, ", -+ "peer_name_id MEDIUMINT UNSIGNED, ", -+ "peer_server_id MEDIUMINT UNSIGNED, ", -+ "at VARCHAR(11), ", -+ "count INT(11) ", -+ ") ENGINE=MyISAM CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> ok; -+ {error, _Reason} -> error -+ end. -+ -+create_stats_table(#state{dbref=DBRef, vhost=VHost}=State) -> -+ SName = stats_table(VHost), -+ Query = ["CREATE TABLE ",SName," (", -+ "owner_id MEDIUMINT UNSIGNED, ", -+ "peer_name_id MEDIUMINT UNSIGNED, ", -+ "peer_server_id MEDIUMINT UNSIGNED, ", -+ "at VARCHAR(11), ", -+ "count INT(11), ", -+ "ext INTEGER DEFAULT NULL, " -+ "INDEX ext_i (ext), " -+ "INDEX(owner_id,peer_name_id,peer_server_id), ", -+ "INDEX(at) ", -+ ") ENGINE=MyISAM CHARACTER SET utf8;" -+ ], -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created stats table for ~p", [VHost]), -+ rebuild_all_stats_int(State), -+ ok; -+ {error, Reason} -> -+ case regexp:match(Reason, "#42S01") of -+ {match, _, _} -> -+ ?MYDEBUG("Stats table for ~p already exists", [VHost]), -+ CheckQuery = ["SHOW COLUMNS FROM ",SName," LIKE 'peer_%_id';"], -+ case sql_query_internal(DBRef, CheckQuery) of -+ {data, Elems} when length(Elems) == 2 -> -+ ?MYDEBUG("Stats table structure is ok", []), -+ ok; -+ _ -> -+ ?INFO_MSG("It seems like stats table structure is invalid. I will drop it and recreate", []), -+ case sql_query_internal(DBRef, ["DROP TABLE ",SName,";"]) of -+ {updated, _} -> -+ ?INFO_MSG("Successfully dropped ~p", [SName]); -+ _ -> -+ ?ERROR_MSG("Failed to drop ~p. You should drop it and restart module", [SName]) -+ end, -+ error -+ end; -+ _ -> -+ ?ERROR_MSG("Failed to create stats table for ~p: ~p", [VHost, Reason]), -+ error -+ end -+ end. -+ -+create_settings_table(#state{dbref=DBRef, vhost=VHost}) -> -+ SName = settings_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",SName," (", -+ "owner_id MEDIUMINT UNSIGNED PRIMARY KEY, ", -+ "dolog_default TINYINT(1) NOT NULL DEFAULT 1, ", -+ "dolog_list TEXT, ", -+ "donotlog_list TEXT ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created settings table for ~p", [VHost]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_users_table(#state{dbref=DBRef, vhost=VHost}) -> -+ SName = users_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",SName," (", -+ "username TEXT NOT NULL, ", -+ "user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, ", -+ "UNIQUE INDEX(username(",?INDEX_SIZE,")) ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created users table for ~p", [VHost]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_servers_table(#state{dbref=DBRef, vhost=VHost}) -> -+ SName = servers_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",SName," (", -+ "server TEXT NOT NULL, ", -+ "server_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, ", -+ "UNIQUE INDEX(server(",?INDEX_SIZE,")) ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created servers table for ~p", [VHost]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_resources_table(#state{dbref=DBRef, vhost=VHost}) -> -+ RName = resources_table(VHost), -+ Query = ["CREATE TABLE IF NOT EXISTS ",RName," (", -+ "resource TEXT NOT NULL, ", -+ "resource_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, ", -+ "UNIQUE INDEX(resource(",?INDEX_SIZE,")) ", -+ ") ENGINE=InnoDB CHARACTER SET utf8;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created resources table for ~p", [VHost]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+create_internals(#state{dbref=DBRef, vhost=VHost}) -> -+ sql_query_internal(DBRef, ["DROP PROCEDURE IF EXISTS ",logmessage_name(VHost),";"]), -+ case sql_query_internal(DBRef, [get_logmessage(VHost)]) of -+ {updated, _} -> -+ ?MYDEBUG("Created logmessage for ~p", [VHost]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% SQL internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+sql_query_internal(DBRef, Query) -> -+ case sql_query_internal_silent(DBRef, Query) of -+ {error, Reason} -> -+ ?ERROR_MSG("~p while ~p", [Reason, lists:append(Query)]), -+ {error, Reason}; -+ Rez -> Rez -+ end. -+ -+sql_query_internal_silent(DBRef, Query) -> -+ ?MYDEBUG("DOING: \"~s\"", [lists:append(Query)]), -+ get_result(mysql_conn:fetch(DBRef, Query, self(), ?MYSQL_TIMEOUT)). -+ -+get_result({updated, MySQLRes}) -> -+ {updated, mysql:get_result_affected_rows(MySQLRes)}; -+get_result({data, MySQLRes}) -> -+ {data, mysql:get_result_rows(MySQLRes)}; -+get_result({error, "query timed out"}) -> -+ {error, "query timed out"}; -+get_result({error, MySQLRes}) -> -+ Reason = mysql:get_result_reason(MySQLRes), -+ {error, Reason}. -+ -+get_user_id(DBRef, VHost, User) -> -+ SQuery = ["SELECT user_id FROM ",users_table(VHost)," ", -+ "WHERE username=\"",User,"\";"], -+ case sql_query_internal(DBRef, SQuery) of -+ {data, []} -> -+ IQuery = ["INSERT INTO ",users_table(VHost)," ", -+ "SET username=\"",User,"\";"], -+ case sql_query_internal_silent(DBRef, IQuery) of -+ {updated, _} -> -+ {data, [[DBIdNew]]} = sql_query_internal(DBRef, SQuery), -+ DBIdNew; -+ {error, Reason} -> -+ % this can be in clustered environment -+ {match, _, _} = regexp:match(Reason, "#23000"), -+ ?ERROR_MSG("Duplicate key name for ~p", [User]), -+ {data, [[ClID]]} = sql_query_internal(DBRef, SQuery), -+ ClID -+ end; -+ {data, [[DBId]]} -> -+ DBId -+ end. -+ -+get_logmessage(VHost) -> -+ UName = users_table(VHost), -+ SName = servers_table(VHost), -+ RName = resources_table(VHost), -+ StName = stats_table(VHost), -+ io_lib:format(" -+CREATE PROCEDURE ~s(tablename TEXT, atdate TEXT, owner TEXT, peer_name TEXT, peer_server TEXT, peer_resource TEXT, mdirection VARCHAR(4), mtype VARCHAR(10), msubject TEXT, mbody TEXT, mtimestamp DOUBLE) -+BEGIN -+ DECLARE ownerID MEDIUMINT UNSIGNED; -+ DECLARE peer_nameID MEDIUMINT UNSIGNED; -+ DECLARE peer_serverID MEDIUMINT UNSIGNED; -+ DECLARE peer_resourceID MEDIUMINT UNSIGNED; -+ DECLARE Vmtype VARCHAR(10); -+ DECLARE Vmtimestamp DOUBLE; -+ DECLARE Vmdirection VARCHAR(4); -+ DECLARE Vmbody TEXT; -+ DECLARE Vmsubject TEXT; -+ DECLARE iq TEXT; -+ DECLARE cq TEXT; -+ DECLARE viewname TEXT; -+ DECLARE notable INT; -+ DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' SET @notable = 1; -+ -+ SET @notable = 0; -+ SET @ownerID = NULL; -+ SET @peer_nameID = NULL; -+ SET @peer_serverID = NULL; -+ SET @peer_resourceID = NULL; -+ -+ SET @Vmtype = mtype; -+ SET @Vmtimestamp = mtimestamp; -+ SET @Vmdirection = mdirection; -+ SET @Vmbody = mbody; -+ SET @Vmsubject = msubject; -+ -+ SELECT user_id INTO @ownerID FROM ~s WHERE username=owner; -+ IF @ownerID IS NULL THEN -+ INSERT INTO ~s SET username=owner; -+ SET @ownerID = LAST_INSERT_ID(); -+ END IF; -+ -+ SELECT user_id INTO @peer_nameID FROM ~s WHERE username=peer_name; -+ IF @peer_nameID IS NULL THEN -+ INSERT INTO ~s SET username=peer_name; -+ SET @peer_nameID = LAST_INSERT_ID(); -+ END IF; -+ -+ SELECT server_id INTO @peer_serverID FROM ~s WHERE server=peer_server; -+ IF @peer_serverID IS NULL THEN -+ INSERT INTO ~s SET server=peer_server; -+ SET @peer_serverID = LAST_INSERT_ID(); -+ END IF; -+ -+ SELECT resource_id INTO @peer_resourceID FROM ~s WHERE resource=peer_resource; -+ IF @peer_resourceID IS NULL THEN -+ INSERT INTO ~s SET resource=peer_resource; -+ SET @peer_resourceID = LAST_INSERT_ID(); -+ END IF; -+ -+ SET @iq = CONCAT(\"INSERT INTO \",tablename,\" (owner_id, peer_name_id, peer_server_id, peer_resource_id, direction, type, subject, body, timestamp) VALUES (@ownerID,@peer_nameID,@peer_serverID,@peer_resourceID,@Vmdirection,@Vmtype,@Vmsubject,@Vmbody,@Vmtimestamp);\"); -+ PREPARE insertmsg FROM @iq; -+ -+ IF @notable = 1 THEN -+ SET @cq = CONCAT(\"CREATE TABLE \",tablename,\" ( -+ owner_id MEDIUMINT UNSIGNED NOT NULL, -+ peer_name_id MEDIUMINT UNSIGNED NOT NULL, -+ peer_server_id MEDIUMINT UNSIGNED NOT NULL, -+ peer_resource_id MEDIUMINT(8) UNSIGNED NOT NULL, -+ direction ENUM('to', 'from') NOT NULL, -+ type ENUM('chat','error','groupchat','headline','normal') NOT NULL, -+ subject TEXT, -+ body TEXT, -+ timestamp DOUBLE NOT NULL, -+ ext INTEGER DEFAULT NULL, -+ INDEX search_i (owner_id, peer_name_id, peer_server_id, peer_resource_id), -+ INDEX ext_i (ext), -+ FULLTEXT (body) -+ ) ENGINE=MyISAM -+ PACK_KEYS=1 -+ CHARACTER SET utf8;\"); -+ PREPARE createtable FROM @cq; -+ EXECUTE createtable; -+ DEALLOCATE PREPARE createtable; -+ -+ SET @viewname = CONCAT(\"`v_\", TRIM(BOTH '`' FROM tablename), \"`\"); -+ SET @cq = CONCAT(\"CREATE OR REPLACE VIEW \",@viewname,\" AS -+ SELECT owner.username AS owner_name, -+ peer.username AS peer_name, -+ servers.server AS peer_server, -+ resources.resource AS peer_resource, -+ messages.direction, -+ messages.type, -+ messages.subject, -+ messages.body, -+ messages.timestamp -+ FROM -+ ~s owner, -+ ~s peer, -+ ~s servers, -+ ~s resources, -+ \", tablename,\" messages -+ WHERE -+ owner.user_id=messages.owner_id and -+ peer.user_id=messages.peer_name_id and -+ servers.server_id=messages.peer_server_id and -+ resources.resource_id=messages.peer_resource_id -+ ORDER BY messages.timestamp;\"); -+ PREPARE createview FROM @cq; -+ EXECUTE createview; -+ DEALLOCATE PREPARE createview; -+ -+ SET @notable = 0; -+ PREPARE insertmsg FROM @iq; -+ EXECUTE insertmsg; -+ ELSEIF @notable = 0 THEN -+ EXECUTE insertmsg; -+ END IF; -+ -+ DEALLOCATE PREPARE insertmsg; -+ -+ IF @notable = 0 THEN -+ UPDATE ~s SET count=count+1 WHERE owner_id=@ownerID AND peer_name_id=@peer_nameID AND peer_server_id=@peer_serverID AND at=atdate; -+ IF ROW_COUNT() = 0 THEN -+ INSERT INTO ~s (owner_id, peer_name_id, peer_server_id, at, count) VALUES (@ownerID, @peer_nameID, @peer_serverID, atdate, 1); -+ END IF; -+ END IF; -+END;", [logmessage_name(VHost),UName,UName,UName,UName,SName,SName,RName,RName,UName,UName,SName,RName,StName,StName]). ---- mod_logdb_pgsql.erl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ mod_logdb_pgsql.erl 2009-02-05 19:20:29.000000000 +0200 -@@ -0,0 +1,1078 @@ -+%%%---------------------------------------------------------------------- -+%%% File : mod_logdb_pgsql.erl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : Posgresql backend for mod_logdb -+%%% Version : trunk -+%%% Id : $Id: mod_logdb_pgsql.erl 1253 2009-02-02 11:10:03Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-module(mod_logdb_pgsql). -+-author('o.palij@gmail.com'). -+ -+-include("mod_logdb.hrl"). -+-include("ejabberd.hrl"). -+-include("jlib.hrl"). -+ -+-behaviour(gen_logdb). -+-behaviour(gen_server). -+ -+% gen_server -+-export([code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2]). -+% gen_mod -+-export([start/2, stop/1]). -+% gen_logdb -+-export([log_message/2, -+ rebuild_stats/1, -+ rebuild_stats_at/2, -+ delete_messages_by_user_at/3, delete_all_messages_by_user_at/3, delete_messages_at/2, -+ get_vhost_stats/1, get_vhost_stats_at/2, get_user_stats/2, get_user_messages_at/3, -+ get_dates/1, -+ get_users_settings/1, get_user_settings/2, set_user_settings/3, -+ drop_user/2]). -+ -+-export([view_table/3]). -+ -+% gen_server call timeout -+-define(CALL_TIMEOUT, 30000). -+-define(PGSQL_TIMEOUT, 60000). -+-define(PROCNAME, mod_logdb_pgsql). -+ -+-import(mod_logdb, [list_to_bool/1, bool_to_list/1, -+ list_to_string/1, string_to_list/1, -+ convert_timestamp_brief/1]). -+ -+-record(state, {dbref, vhost, server, port, db, user, password, schema}). -+ -+% replace "." with "_" -+escape_vhost(VHost) -> lists:map(fun(46) -> 95; -+ (A) -> A -+ end, VHost). -+ -+prefix(Schema) -> -+ Schema ++ ".\"" ++ "logdb_". -+ -+suffix(VHost) -> -+ "_" ++ escape_vhost(VHost) ++ "\"". -+ -+messages_table(VHost, Schema, Date) -> -+ prefix(Schema) ++ "messages_" ++ Date ++ suffix(VHost). -+ -+view_table(VHost, Schema, Date) -> -+ Table = messages_table(VHost, Schema, Date), -+ TablewoS = lists:sublist(Table, length(Schema) + 3, length(Table) - length(Schema) - 3), -+ lists:append([Schema, ".\"v_", TablewoS, "\""]). -+ -+stats_table(VHost, Schema) -> -+ prefix(Schema) ++ "stats" ++ suffix(VHost). -+ -+temp_table(VHost, Schema) -> -+ prefix(Schema) ++ "temp" ++ suffix(VHost). -+ -+settings_table(VHost, Schema) -> -+ prefix(Schema) ++ "settings" ++ suffix(VHost). -+ -+users_table(VHost, Schema) -> -+ prefix(Schema) ++ "users" ++ suffix(VHost). -+servers_table(VHost, Schema) -> -+ prefix(Schema) ++ "servers" ++ suffix(VHost). -+resources_table(VHost, Schema) -> -+ prefix(Schema) ++ "resources" ++ suffix(VHost). -+ -+logmessage_name(VHost, Schema) -> -+ prefix(Schema) ++ "logmessage" ++ suffix(VHost). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_mod callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+start(VHost, Opts) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:start({local, Proc}, ?MODULE, [VHost, Opts], []). -+ -+stop(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {stop}, ?CALL_TIMEOUT). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_server callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+init([VHost, Opts]) -> -+ Server = gen_mod:get_opt(server, Opts, "localhost"), -+ DB = gen_mod:get_opt(db, Opts, "ejabberd_logdb"), -+ User = gen_mod:get_opt(user, Opts, "root"), -+ Port = gen_mod:get_opt(port, Opts, 5432), -+ Password = gen_mod:get_opt(password, Opts, ""), -+ Schema = gen_mod:get_opt(schema, Opts, "public"), -+ -+ ?MYDEBUG("Starting pgsql backend for ~p", [VHost]), -+ -+ St = #state{vhost=VHost, -+ server=Server, port=Port, db=DB, -+ user=User, password=Password, -+ schema=Schema}, -+ -+ case open_pgsql_connection(St) of -+ {ok, DBRef} -> -+ State = St#state{dbref=DBRef}, -+ ok = create_internals(State), -+ ok = create_stats_table(State), -+ ok = create_settings_table(State), -+ ok = create_users_table(State), -+ ok = create_servers_table(State), -+ ok = create_resources_table(State), -+ erlang:monitor(process, DBRef), -+ {ok, State}; -+ % this does not work -+ {error, Reason} -> -+ ?ERROR_MSG("PgSQL connection failed: ~p~n", [Reason]), -+ {stop, db_connection_failed}; -+ % and this too, becouse pgsql_conn do exit() which can not be catched -+ {'EXIT', Rez} -> -+ ?ERROR_MSG("Rez: ~p~n", [Rez]), -+ {stop, db_connection_failed} -+ end. -+ -+open_pgsql_connection(#state{server=Server, port=Port, db=DB, schema=Schema, -+ user=User, password=Password} = _State) -> -+ {ok, DBRef} = pgsql:connect(Server, DB, User, Password, Port), -+ {updated, _} = sql_query_internal(DBRef, ["SET SEARCH_PATH TO ",Schema,";"]), -+ {ok, DBRef}. -+ -+close_pgsql_connection(DBRef) -> -+ ?MYDEBUG("Closing ~p pgsql connection", [DBRef]), -+ pgsql:terminate(DBRef). -+ -+handle_call({log_message, Msg}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ Date = convert_timestamp_brief(Msg#msg.timestamp), -+ TableName = messages_table(VHost, Schema, Date), -+ ViewName = view_table(VHost, Schema, Date), -+ -+ Query = [ "SELECT ", logmessage_name(VHost, Schema)," " -+ "('", TableName, "',", -+ "'", ViewName, "',", -+ "'", Date, "',", -+ "'", Msg#msg.owner_name, "',", -+ "'", Msg#msg.peer_name, "',", -+ "'", Msg#msg.peer_server, "',", -+ "'", ejabberd_odbc:escape(Msg#msg.peer_resource), "',", -+ "'", atom_to_list(Msg#msg.direction), "',", -+ "'", Msg#msg.type, "',", -+ "'", ejabberd_odbc:escape(Msg#msg.subject), "',", -+ "'", ejabberd_odbc:escape(Msg#msg.body), "',", -+ "'", Msg#msg.timestamp, "');"], -+ -+ case sql_query_internal_silent(DBRef, Query) of -+ % TODO: change this -+ {data, [{"0"}]} -> -+ ?MYDEBUG("Logged ok for ~p, peer: ~p", [Msg#msg.owner_name++"@"++VHost, -+ Msg#msg.peer_name++"@"++Msg#msg.peer_server]), -+ ok; -+ {error, _Reason} -> -+ error -+ end, -+ {reply, ok, State}; -+handle_call({rebuild_stats_at, Date}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ Reply = rebuild_stats_at_int(DBRef, VHost, Schema, Date), -+ {reply, Reply, State}; -+handle_call({delete_messages_by_user_at, [], _Date}, _From, State) -> -+ {reply, error, State}; -+handle_call({delete_messages_by_user_at, Msgs, Date}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ Temp = lists:flatmap(fun(#msg{timestamp=Timestamp} = _Msg) -> -+ ["'",Timestamp,"'",","] -+ end, Msgs), -+ -+ Temp1 = lists:append([lists:sublist(Temp, length(Temp)-1), ");"]), -+ -+ Query = ["DELETE FROM ",messages_table(VHost, Schema, Date)," ", -+ "WHERE timestamp IN (", Temp1], -+ -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ rebuild_stats_at_int(DBRef, VHost, Schema, Date); -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({delete_all_messages_by_user_at, User, Date}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ ok = delete_all_messages_by_user_at_int(DBRef, Schema, User, VHost, Date), -+ ok = delete_stats_by_user_at_int(DBRef, Schema, User, VHost, Date), -+ {reply, ok, State}; -+handle_call({delete_messages_at, Date}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ {updated, _} = sql_query_internal(DBRef, ["DROP VIEW ",view_table(VHost, Schema, Date),";"]), -+ Reply = -+ case sql_query_internal(DBRef, ["DROP TABLE ",messages_table(VHost, Schema, Date)," CASCADE;"]) of -+ {updated, _} -> -+ Query = ["DELETE FROM ",stats_table(VHost, Schema)," " -+ "WHERE at='",Date,"';"], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ok; -+ {error, _} -> -+ error -+ end; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ SName = stats_table(VHost, Schema), -+ Query = ["SELECT at, sum(count) ", -+ "FROM ",SName," ", -+ "GROUP BY at ", -+ "ORDER BY DATE(at) DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Recs} -> -+ {ok, [ {Date, list_to_integer(Count)} || {Date, Count} <- Recs]}; -+ {error, Reason} -> -+ % TODO: Duplicate error message ? -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_vhost_stats_at, Date}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ SName = stats_table(VHost, Schema), -+ Query = ["SELECT username, sum(count) AS allcount ", -+ "FROM ",SName," ", -+ "JOIN ",users_table(VHost, Schema)," ON owner_id=user_id ", -+ "WHERE at='",Date,"' ", -+ "GROUP BY username ", -+ "ORDER BY allcount DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Recs} -> -+ RFun = fun({User, Count}) -> -+ {User, list_to_integer(Count)} -+ end, -+ {ok, lists:reverse(lists:keysort(2, lists:map(RFun, Recs)))}; -+ {error, Reason} -> -+ % TODO: -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_user_stats, User}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ {reply, get_user_stats_int(DBRef, Schema, User, VHost), State}; -+handle_call({get_user_messages_at, User, Date}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ Query = ["SELECT peer_name,", -+ "peer_server,", -+ "peer_resource,", -+ "direction," -+ "type," -+ "subject," -+ "body," -+ "timestamp " -+ "FROM ",view_table(VHost, Schema, Date)," " -+ "WHERE owner_name='",User,"';"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Recs} -> -+ Fun = fun({Peer_name, Peer_server, Peer_resource, -+ Direction, -+ Type, -+ Subject, Body, -+ Timestamp}) -> -+ #msg{peer_name=Peer_name, peer_server=Peer_server, peer_resource=Peer_resource, -+ direction=list_to_atom(Direction), -+ type=Type, -+ subject=Subject, body=Body, -+ timestamp=Timestamp} -+ end, -+ {ok, lists:map(Fun, Recs)}; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_dates}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ SName = stats_table(VHost, Schema), -+ Query = ["SELECT at ", -+ "FROM ",SName," ", -+ "GROUP BY at ", -+ "ORDER BY at DESC;" -+ ], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Result} -> -+ [ Date || {Date} <- Result ]; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_users_settings}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ Query = ["SELECT username,dolog_default,dolog_list,donotlog_list ", -+ "FROM ",settings_table(VHost, Schema)," ", -+ "JOIN ",users_table(VHost, Schema)," ON user_id=owner_id;"], -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {data, Recs} -> -+ {ok, [#user_settings{owner_name=Owner, -+ dolog_default=list_to_bool(DoLogDef), -+ dolog_list=string_to_list(DoLogL), -+ donotlog_list=string_to_list(DoNotLogL) -+ } || {Owner, DoLogDef, DoLogL, DoNotLogL} <- Recs]}; -+ {error, Reason} -> -+ {error, Reason} -+ end, -+ {reply, Reply, State}; -+handle_call({get_user_settings, User}, _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ Query = ["SELECT dolog_default,dolog_list,donotlog_list ", -+ "FROM ",settings_table(VHost, Schema)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost, Schema)," WHERE username='",User,"');"], -+ Reply = -+ case sql_query_internal_silent(DBRef, Query) of -+ {data, []} -> -+ {ok, []}; -+ {data, [{DoLogDef, DoLogL, DoNotLogL}]} -> -+ {ok, #user_settings{owner_name=User, -+ dolog_default=list_to_bool(DoLogDef), -+ dolog_list=string_to_list(DoLogL), -+ donotlog_list=string_to_list(DoNotLogL)}}; -+ {error, Reason} -> -+ ?ERROR_MSG("Failed to get_user_settings for ~p@~p: ~p", [User, VHost, Reason]), -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({set_user_settings, User, #user_settings{dolog_default=DoLogDef, -+ dolog_list=DoLogL, -+ donotlog_list=DoNotLogL}}, -+ _From, #state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ User_id = get_user_id(DBRef, VHost, Schema, User), -+ Query = ["UPDATE ",settings_table(VHost, Schema)," ", -+ "SET dolog_default=",bool_to_list(DoLogDef),", ", -+ "dolog_list='",list_to_string(DoLogL),"', ", -+ "donotlog_list='",list_to_string(DoNotLogL),"' ", -+ "WHERE owner_id=",User_id,";"], -+ -+ Reply = -+ case sql_query_internal(DBRef, Query) of -+ {updated, 0} -> -+ IQuery = ["INSERT INTO ",settings_table(VHost, Schema)," ", -+ "(owner_id, dolog_default, dolog_list, donotlog_list) ", -+ "VALUES ", -+ "(",User_id,", ",bool_to_list(DoLogDef),",'",list_to_string(DoLogL),"','",list_to_string(DoNotLogL),"');"], -+ case sql_query_internal(DBRef, IQuery) of -+ {updated, 1} -> -+ ?MYDEBUG("New settings for ~s@~s", [User, VHost]), -+ ok; -+ {error, _} -> -+ error -+ end; -+ {updated, 1} -> -+ ?MYDEBUG("Updated settings for ~s@~s", [User, VHost]), -+ ok; -+ {error, _} -> -+ error -+ end, -+ {reply, Reply, State}; -+handle_call({stop}, _From, State) -> -+ ?MYDEBUG("Stoping pgsql backend for ~p", [State#state.vhost]), -+ {stop, normal, ok, State}; -+handle_call(Msg, _From, State) -> -+ ?INFO_MSG("Got call Msg: ~p, State: ~p", [Msg, State]), -+ {noreply, State}. -+ -+ -+handle_cast({rebuild_stats}, State) -> -+ rebuild_all_stats_int(State), -+ {noreply, State}; -+handle_cast({drop_user, User}, #state{vhost=VHost, schema=Schema}=State) -> -+ Fun = fun() -> -+ {ok, DBRef} = open_pgsql_connection(State), -+ {ok, Dates} = get_user_stats_int(DBRef, Schema, User, VHost), -+ MDResult = lists:map(fun({Date, _}) -> -+ delete_all_messages_by_user_at_int(DBRef, Schema, User, VHost, Date) -+ end, Dates), -+ StDResult = delete_all_stats_by_user_int(DBRef, Schema, User, VHost), -+ SDResult = delete_user_settings_int(DBRef, Schema, User, VHost), -+ case lists:all(fun(Result) when Result == ok -> -+ true; -+ (Result) when Result == error -> -+ false -+ end, lists:append([MDResult, [StDResult], [SDResult]])) of -+ true -> -+ ?INFO_MSG("Removed ~s@~s", [User, VHost]); -+ false -> -+ ?ERROR_MSG("Failed to remove ~s@~s", [User, VHost]) -+ end, -+ close_pgsql_connection(DBRef) -+ end, -+ spawn(Fun), -+ {noreply, State}; -+handle_cast(Msg, State) -> -+ ?INFO_MSG("Got cast Msg:~p, State:~p", [Msg, State]), -+ {noreply, State}. -+ -+handle_info({'DOWN', _MonitorRef, process, _Pid, _Info}, State) -> -+ {stop, connection_dropped, State}; -+handle_info(Info, State) -> -+ ?INFO_MSG("Got Info:~p, State:~p", [Info, State]), -+ {noreply, State}. -+ -+terminate(_Reason, #state{dbref=DBRef}=_State) -> -+ close_pgsql_connection(DBRef), -+ ok. -+ -+code_change(_OldVsn, State, _Extra) -> -+ {ok, State}. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+log_message(VHost, Msg) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {log_message, Msg}, ?CALL_TIMEOUT). -+rebuild_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {rebuild_stats}). -+rebuild_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {rebuild_stats_at, Date}, ?CALL_TIMEOUT). -+delete_messages_by_user_at(VHost, Msgs, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_by_user_at, Msgs, Date}, ?CALL_TIMEOUT). -+delete_all_messages_by_user_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_all_messages_by_user_at, User, Date}, ?CALL_TIMEOUT). -+delete_messages_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {delete_messages_at, Date}, ?CALL_TIMEOUT). -+get_vhost_stats(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats}, ?CALL_TIMEOUT). -+get_vhost_stats_at(VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_vhost_stats_at, Date}, ?CALL_TIMEOUT). -+get_user_stats(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_stats, User}, ?CALL_TIMEOUT). -+get_user_messages_at(User, VHost, Date) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_messages_at, User, Date}, ?CALL_TIMEOUT). -+get_dates(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_dates}, ?CALL_TIMEOUT). -+get_users_settings(VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_users_settings}, ?CALL_TIMEOUT). -+get_user_settings(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {get_user_settings, User}, ?CALL_TIMEOUT). -+set_user_settings(User, VHost, Set) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:call(Proc, {set_user_settings, User, Set}, ?CALL_TIMEOUT). -+drop_user(User, VHost) -> -+ Proc = gen_mod:get_module_proc(VHost, ?PROCNAME), -+ gen_server:cast(Proc, {drop_user, User}). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+get_dates_int(DBRef, VHost) -> -+ Query = ["SELECT n.nspname as \"Schema\", -+ c.relname as \"Name\", -+ CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as \"Type\", -+ r.rolname as \"Owner\" -+ FROM pg_catalog.pg_class c -+ JOIN pg_catalog.pg_roles r ON r.oid = c.relowner -+ LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace -+ WHERE c.relkind IN ('r','') -+ AND n.nspname NOT IN ('pg_catalog', 'pg_toast') -+ AND c.relname ~ '^(.*",escape_vhost(VHost),".*)$' -+ AND pg_catalog.pg_table_is_visible(c.oid) -+ ORDER BY 1,2;"], -+ case sql_query_internal(DBRef, Query) of -+ {data, Recs} -> -+ lists:foldl(fun({_Schema, Table, _Type, _Owner}, Dates) -> -+ case regexp:match(Table,"[0-9]+-[0-9]+-[0-9]+") of -+ {match, S, E} -> -+ lists:append(Dates, [lists:sublist(Table,S,E)]); -+ nomatch -> -+ Dates -+ end -+ end, [], Recs); -+ {error, _} -> -+ [] -+ end. -+ -+rebuild_all_stats_int(#state{vhost=VHost, schema=Schema}=State) -> -+ Fun = fun() -> -+ {ok, DBRef} = open_pgsql_connection(State), -+ ok = delete_nonexistent_stats(DBRef, Schema, VHost), -+ case lists:filter(fun(Date) -> -+ case catch rebuild_stats_at_int(DBRef, VHost, Schema, Date) of -+ ok -> false; -+ error -> true; -+ {'EXIT', _} -> true -+ end -+ end, get_dates_int(DBRef, VHost)) of -+ [] -> ok; -+ FTables -> -+ ?ERROR_MSG("Failed to rebuild stats for ~p dates", [FTables]), -+ error -+ end, -+ close_pgsql_connection(DBRef) -+ end, -+ spawn(Fun). -+ -+rebuild_stats_at_int(DBRef, VHost, Schema, Date) -> -+ TempTable = temp_table(VHost, Schema), -+ Fun = -+ fun() -> -+ Table = messages_table(VHost, Schema, Date), -+ STable = stats_table(VHost, Schema), -+ -+ DQuery = [ "DELETE FROM ",STable," ", -+ "WHERE at='",Date,"';"], -+ -+ ok = create_temp_table(DBRef, VHost, Schema), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",Table," IN ACCESS EXCLUSIVE MODE;"]), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",TempTable," IN ACCESS EXCLUSIVE MODE;"]), -+ SQuery = ["INSERT INTO ",TempTable," ", -+ "(owner_id,peer_name_id,peer_server_id,at,count) ", -+ "SELECT owner_id,peer_name_id,peer_server_id,'",Date,"'",",count(*) ", -+ "FROM ",Table," GROUP BY owner_id,peer_name_id,peer_server_id;"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, 0} -> -+ Count = sql_query_internal(DBRef, ["SELECT count(*) FROM ",Table,";"]), -+ case Count of -+ {data, [{"0"}]} -> -+ {updated, _} = sql_query_internal(DBRef, ["DROP VIEW ",view_table(VHost, Schema, Date),";"]), -+ {updated, _} = sql_query_internal(DBRef, ["DROP TABLE ",Table," CASCADE;"]), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",STable," IN ACCESS EXCLUSIVE MODE;"]), -+ {updated, _} = sql_query_internal(DBRef, DQuery), -+ ok; -+ _ -> -+ ?ERROR_MSG("Failed to calculate stats for ~s table! Count was ~p.", [Date, Count]), -+ error -+ end; -+ {updated, _} -> -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",STable," IN ACCESS EXCLUSIVE MODE;"]), -+ {updated, _} = sql_query_internal(DBRef, ["LOCK TABLE ",TempTable," IN ACCESS EXCLUSIVE MODE;"]), -+ {updated, _} = sql_query_internal(DBRef, DQuery), -+ SQuery1 = ["INSERT INTO ",STable," ", -+ "(owner_id,peer_name_id,peer_server_id,at,count) ", -+ "SELECT owner_id,peer_name_id,peer_server_id,at,count ", -+ "FROM ",TempTable,";"], -+ case sql_query_internal(DBRef, SQuery1) of -+ {updated, _} -> ok; -+ {error, _} -> error -+ end; -+ {error, _} -> error -+ end -+ end, % fun -+ -+ case sql_transaction_internal(DBRef, Fun) of -+ {atomic, _} -> -+ ?INFO_MSG("Rebuilded stats for ~p at ~p", [VHost, Date]), -+ ok; -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to rebuild stats for ~s table: ~p.", [Date, Reason]), -+ error -+ end, -+ sql_query_internal(DBRef, ["DROP TABLE ",TempTable,";"]), -+ ok. -+ -+delete_nonexistent_stats(DBRef, Schema, VHost) -> -+ Dates = get_dates_int(DBRef, VHost), -+ STable = stats_table(VHost, Schema), -+ -+ Temp = lists:flatmap(fun(Date) -> -+ ["'",Date,"'",","] -+ end, Dates), -+ -+ case Temp of -+ [] -> -+ ok; -+ _ -> -+ % replace last "," with ");" -+ Temp1 = lists:append([lists:sublist(Temp, length(Temp)-1), ");"]), -+ Query = ["DELETE FROM ",STable," ", -+ "WHERE at NOT IN (", Temp1], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ok; -+ {error, _} -> -+ error -+ end -+ end. -+ -+get_user_stats_int(DBRef, Schema, User, VHost) -> -+ SName = stats_table(VHost, Schema), -+ UName = users_table(VHost, Schema), -+ Query = ["SELECT stats.at, sum(stats.count) ", -+ "FROM ",UName," AS users ", -+ "JOIN ",SName," AS stats ON owner_id=user_id " -+ "WHERE users.username='",User,"' ", -+ "GROUP BY stats.at " -+ "ORDER BY DATE(at) DESC;" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {data, Recs} -> -+ {ok, [ {Date, list_to_integer(Count)} || {Date, Count} <- Recs ]}; -+ {error, Result} -> -+ {error, Result} -+ end. -+ -+delete_all_messages_by_user_at_int(DBRef, Schema, User, VHost, Date) -> -+ DQuery = ["DELETE FROM ",messages_table(VHost, Schema, Date)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost, Schema)," WHERE username='",User,"');"], -+ case sql_query_internal(DBRef, DQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped messages for ~s@~s at ~s", [User, VHost, Date]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+delete_all_stats_by_user_int(DBRef, Schema, User, VHost) -> -+ SQuery = ["DELETE FROM ",stats_table(VHost, Schema)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost, Schema)," WHERE username='",User,"');"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped all stats for ~s@~s", [User, VHost]), -+ ok; -+ {error, _} -> error -+ end. -+ -+delete_stats_by_user_at_int(DBRef, Schema, User, VHost, Date) -> -+ SQuery = ["DELETE FROM ",stats_table(VHost, Schema)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost, Schema)," WHERE username='",User,"') ", -+ "AND at='",Date,"';"], -+ case sql_query_internal(DBRef, SQuery) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped stats for ~s@~s at ~s", [User, VHost, Date]), -+ ok; -+ {error, _} -> error -+ end. -+ -+delete_user_settings_int(DBRef, Schema, User, VHost) -> -+ Query = ["DELETE FROM ",settings_table(VHost, Schema)," ", -+ "WHERE owner_id=(SELECT user_id FROM ",users_table(VHost, Schema)," WHERE username='",User,"');"], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> -+ ?INFO_MSG("Dropped ~s@~s settings", [User, VHost]), -+ ok; -+ {error, Reason} -> -+ ?ERROR_MSG("Failed to drop ~s@~s settings: ~p", [User, VHost, Reason]), -+ error -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% tables internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+create_temp_table(DBRef, VHost, Schema) -> -+ TName = temp_table(VHost, Schema), -+ Query = ["CREATE TABLE ",TName," (", -+ "owner_id INTEGER, ", -+ "peer_name_id INTEGER, ", -+ "peer_server_id INTEGER, ", -+ "at VARCHAR(20), ", -+ "count INTEGER ", -+ ");" -+ ], -+ case sql_query_internal(DBRef, Query) of -+ {updated, _} -> ok; -+ {error, _Reason} -> error -+ end. -+ -+create_stats_table(#state{dbref=DBRef, vhost=VHost, schema=Schema}=State) -> -+ SName = stats_table(VHost, Schema), -+ -+ Fun = -+ fun() -> -+ Query = ["CREATE TABLE ",SName," (", -+ "owner_id INTEGER, ", -+ "peer_name_id INTEGER, ", -+ "peer_server_id INTEGER, ", -+ "at VARCHAR(20), ", -+ "count integer", -+ ");" -+ ], -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ {updated, _} = sql_query_internal(DBRef, ["CREATE INDEX \"s_search_i_",Schema,"_",escape_vhost(VHost),"\" ON ",SName," (owner_id, peer_name_id, peer_server_id);"]), -+ {updated, _} = sql_query_internal(DBRef, ["CREATE INDEX \"s_at_i_",Schema,"_",escape_vhost(VHost),"\" ON ",SName," (at);"]), -+ created; -+ {error, Reason} -> -+ case lists:keysearch(code, 1, Reason) of -+ {value, {code, "42P07"}} -> -+ exists; -+ _ -> -+ ?ERROR_MSG("Failed to create stats table for ~p: ~p", [VHost, Reason]), -+ error -+ end -+ end -+ end, -+ case sql_transaction_internal(DBRef, Fun) of -+ {atomic, created} -> -+ ?MYDEBUG("Created stats table for ~p", [VHost]), -+ rebuild_all_stats_int(State), -+ ok; -+ {atomic, exists} -> -+ ?MYDEBUG("Stats table for ~p already exists", [VHost]), -+ {match, F, L} = regexp:match(SName, "\".*\""), -+ QTable = lists:sublist(SName, F+1, L-2), -+ OIDQuery = ["SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname='",QTable,"' AND pg_catalog.pg_table_is_visible(c.oid);"], -+ {data,[{OID}]} = sql_query_internal(DBRef, OIDQuery), -+ CheckQuery = ["SELECT a.attname FROM pg_catalog.pg_attribute a WHERE a.attrelid = '",OID,"' AND a.attnum > 0 AND NOT a.attisdropped AND a.attname ~ '^peer_.*_id$';"], -+ case sql_query_internal(DBRef, CheckQuery) of -+ {data, Elems} when length(Elems) == 2 -> -+ ?MYDEBUG("Stats table structure is ok", []), -+ ok; -+ _ -> -+ ?INFO_MSG("It seems like stats table structure is invalid. I will drop it and recreate", []), -+ case sql_query_internal(DBRef, ["DROP TABLE ",SName,";"]) of -+ {updated, _} -> -+ ?INFO_MSG("Successfully dropped ~p", [SName]); -+ _ -> -+ ?ERROR_MSG("Failed to drop ~p. You should drop it and restart module", [SName]) -+ end, -+ error -+ end; -+ {error, _} -> error -+ end. -+ -+create_settings_table(#state{dbref=DBRef, vhost=VHost, schema=Schema}) -> -+ SName = settings_table(VHost, Schema), -+ Query = ["CREATE TABLE ",SName," (", -+ "owner_id INTEGER PRIMARY KEY, ", -+ "dolog_default BOOLEAN, ", -+ "dolog_list TEXT DEFAULT '', ", -+ "donotlog_list TEXT DEFAULT ''", -+ ");" -+ ], -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ ?MYDEBUG("Created settings table for ~p", [VHost]), -+ ok; -+ {error, Reason} -> -+ case lists:keysearch(code, 1, Reason) of -+ {value, {code, "42P07"}} -> -+ ?MYDEBUG("Settings table for ~p already exists", [VHost]), -+ ok; -+ _ -> -+ ?ERROR_MSG("Failed to create settings table for ~p: ~p", [VHost, Reason]), -+ error -+ end -+ end. -+ -+create_users_table(#state{dbref=DBRef, vhost=VHost, schema=Schema}) -> -+ SName = users_table(VHost, Schema), -+ -+ Fun = -+ fun() -> -+ Query = ["CREATE TABLE ",SName," (", -+ "username TEXT UNIQUE, ", -+ "user_id SERIAL PRIMARY KEY", -+ ");" -+ ], -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ {updated, _} = sql_query_internal(DBRef, ["CREATE INDEX \"username_i_",Schema,"_",escape_vhost(VHost),"\" ON ",SName," (username);"]), -+ created; -+ {error, Reason} -> -+ case lists:keysearch(code, 1, Reason) of -+ {value, {code, "42P07"}} -> -+ exists; -+ _ -> -+ ?ERROR_MSG("Failed to create users table for ~p: ~p", [VHost, Reason]), -+ error -+ end -+ end -+ end, -+ case sql_transaction_internal(DBRef, Fun) of -+ {atomic, created} -> -+ ?MYDEBUG("Created users table for ~p", [VHost]), -+ ok; -+ {atomic, exists} -> -+ ?MYDEBUG("Users table for ~p already exists", [VHost]), -+ ok; -+ {aborted, _} -> error -+ end. -+ -+create_servers_table(#state{dbref=DBRef, vhost=VHost, schema=Schema}) -> -+ SName = servers_table(VHost, Schema), -+ Fun = -+ fun() -> -+ Query = ["CREATE TABLE ",SName," (", -+ "server TEXT UNIQUE, ", -+ "server_id SERIAL PRIMARY KEY", -+ ");" -+ ], -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ {updated, _} = sql_query_internal(DBRef, ["CREATE INDEX \"server_i_",Schema,"_",escape_vhost(VHost),"\" ON ",SName," (server);"]), -+ created; -+ {error, Reason} -> -+ case lists:keysearch(code, 1, Reason) of -+ {value, {code, "42P07"}} -> -+ exists; -+ _ -> -+ ?ERROR_MSG("Failed to create servers table for ~p: ~p", [VHost, Reason]), -+ error -+ end -+ end -+ end, -+ case sql_transaction_internal(DBRef, Fun) of -+ {atomic, created} -> -+ ?MYDEBUG("Created servers table for ~p", [VHost]), -+ ok; -+ {atomic, exists} -> -+ ?MYDEBUG("Servers table for ~p already exists", [VHost]), -+ ok; -+ {aborted, _} -> error -+ end. -+ -+create_resources_table(#state{dbref=DBRef, vhost=VHost, schema=Schema}) -> -+ RName = resources_table(VHost, Schema), -+ Fun = fun() -> -+ Query = ["CREATE TABLE ",RName," (", -+ "resource TEXT UNIQUE, ", -+ "resource_id SERIAL PRIMARY KEY", -+ ");" -+ ], -+ case sql_query_internal_silent(DBRef, Query) of -+ {updated, _} -> -+ {updated, _} = sql_query_internal(DBRef, ["CREATE INDEX \"resource_i_",Schema,"_",escape_vhost(VHost),"\" ON ",RName," (resource);"]), -+ created; -+ {error, Reason} -> -+ case lists:keysearch(code, 1, Reason) of -+ {value, {code, "42P07"}} -> -+ exists; -+ _ -> -+ ?ERROR_MSG("Failed to create users table for ~p: ~p", [VHost, Reason]), -+ error -+ end -+ end -+ end, -+ case sql_transaction_internal(DBRef, Fun) of -+ {atomic, created} -> -+ ?MYDEBUG("Created resources table for ~p", [VHost]), -+ ok; -+ {atomic, exists} -> -+ ?MYDEBUG("Resources table for ~p already exists", [VHost]), -+ ok; -+ {aborted, _} -> error -+ end. -+ -+create_internals(#state{dbref=DBRef, vhost=VHost, schema=Schema}) -> -+ sql_query_internal(DBRef, ["DROP FUNCTION IF EXISTS ",logmessage_name(VHost,Schema)," (tbname TEXT, atdt TEXT, owner TEXT, peer_name TEXT, peer_server TEXT, peer_resource TEXT, mdirection VARCHAR(4), mtype VARCHAR(9), msubj TEXT, mbody TEXT, mtimestamp DOUBLE PRECISION);"]), -+ case sql_query_internal(DBRef, [get_logmessage(VHost, Schema)]) of -+ {updated, _} -> -+ ?MYDEBUG("Created logmessage for ~p", [VHost]), -+ ok; -+ {error, _} -> -+ error -+ end. -+ -+get_user_id(DBRef, VHost, Schema, User) -> -+ SQuery = ["SELECT user_id FROM ",users_table(VHost, Schema)," ", -+ "WHERE username='",User,"';"], -+ case sql_query_internal(DBRef, SQuery) of -+ {data, []} -> -+ IQuery = ["INSERT INTO ",users_table(VHost, Schema)," ", -+ "VALUES ('",User,"');"], -+ case sql_query_internal_silent(DBRef, IQuery) of -+ {updated, _} -> -+ {data, [{DBIdNew}]} = sql_query_internal(DBRef, SQuery), -+ DBIdNew; -+ {error, Reason} -> -+ % this can be in clustered environment -+ {value, {code, "23505"}} = lists:keysearch(code, 1, Reason), -+ ?ERROR_MSG("Duplicate key name for ~p", [User]), -+ {data, [{ClID}]} = sql_query_internal(DBRef, SQuery), -+ ClID -+ end; -+ {data, [{DBId}]} -> -+ DBId -+ end. -+ -+get_logmessage(VHost,Schema) -> -+ UName = users_table(VHost,Schema), -+ SName = servers_table(VHost,Schema), -+ RName = resources_table(VHost,Schema), -+ StName = stats_table(VHost,Schema), -+ io_lib:format("CREATE OR REPLACE FUNCTION ~s (tbname TEXT, vname TEXT, atdt TEXT, owner TEXT, peer_name TEXT, peer_server TEXT, peer_resource TEXT, mdirection VARCHAR(4), mtype VARCHAR(9), msubj TEXT, mbody TEXT, mtimestamp DOUBLE PRECISION) RETURNS INTEGER AS $$ -+DECLARE -+ ownerID INTEGER; -+ peer_nameID INTEGER; -+ peer_serverID INTEGER; -+ peer_resourceID INTEGER; -+ tablename ALIAS for $1; -+ viewname ALIAS for $2; -+ atdate ALIAS for $3; -+BEGIN -+ SELECT INTO ownerID user_id FROM ~s WHERE username = owner; -+ IF NOT FOUND THEN -+ INSERT INTO ~s (username) VALUES (owner); -+ ownerID := lastval(); -+ END IF; -+ -+ SELECT INTO peer_nameID user_id FROM ~s WHERE username = peer_name; -+ IF NOT FOUND THEN -+ INSERT INTO ~s (username) VALUES (peer_name); -+ peer_nameID := lastval(); -+ END IF; -+ -+ SELECT INTO peer_serverID server_id FROM ~s WHERE server = peer_server; -+ IF NOT FOUND THEN -+ INSERT INTO ~s (server) VALUES (peer_server); -+ peer_serverID := lastval(); -+ END IF; -+ -+ SELECT INTO peer_resourceID resource_id FROM ~s WHERE resource = peer_resource; -+ IF NOT FOUND THEN -+ INSERT INTO ~s (resource) VALUES (peer_resource); -+ peer_resourceID := lastval(); -+ END IF; -+ -+ BEGIN -+ EXECUTE 'INSERT INTO ' || tablename || ' (owner_id, peer_name_id, peer_server_id, peer_resource_id, direction, type, subject, body, timestamp) VALUES (' || ownerID || ',' || peer_nameID || ',' || peer_serverID || ',' || peer_resourceID || ',''' || mdirection || ''',''' || mtype || ''',' || quote_literal(msubj) || ',' || quote_literal(mbody) || ',' || mtimestamp || ')'; -+ EXCEPTION WHEN undefined_table THEN -+ EXECUTE 'CREATE TABLE ' || tablename || ' (' || -+ 'owner_id INTEGER, ' || -+ 'peer_name_id INTEGER, ' || -+ 'peer_server_id INTEGER, ' || -+ 'peer_resource_id INTEGER, ' || -+ 'direction VARCHAR(4) CHECK (direction IN (''to'',''from'')), ' || -+ 'type VARCHAR(9) CHECK (type IN (''chat'',''error'',''groupchat'',''headline'',''normal'')), ' || -+ 'subject TEXT, ' || -+ 'body TEXT, ' || -+ 'timestamp DOUBLE PRECISION)'; -+ EXECUTE 'CREATE INDEX \"search_i_' || '~s' || '_' || atdate || '_' || '~s' || '\"' || ' ON ' || tablename || ' (owner_id, peer_name_id, peer_server_id, peer_resource_id)'; -+ -+ EXECUTE 'CREATE OR REPLACE VIEW ' || viewname || ' AS ' || -+ 'SELECT owner.username AS owner_name, ' || -+ 'peer.username AS peer_name, ' || -+ 'servers.server AS peer_server, ' || -+ 'resources.resource AS peer_resource, ' || -+ 'messages.direction, ' || -+ 'messages.type, ' || -+ 'messages.subject, ' || -+ 'messages.body, ' || -+ 'messages.timestamp ' || -+ 'FROM ' || -+ '~s owner, ' || -+ '~s peer, ' || -+ '~s servers, ' || -+ '~s resources, ' || -+ tablename || ' messages ' || -+ 'WHERE ' || -+ 'owner.user_id=messages.owner_id and ' || -+ 'peer.user_id=messages.peer_name_id and ' || -+ 'servers.server_id=messages.peer_server_id and ' || -+ 'resources.resource_id=messages.peer_resource_id ' || -+ 'ORDER BY messages.timestamp'; -+ -+ EXECUTE 'INSERT INTO ' || tablename || ' (owner_id, peer_name_id, peer_server_id, peer_resource_id, direction, type, subject, body, timestamp) VALUES (' || ownerID || ',' || peer_nameID || ',' || peer_serverID || ',' || peer_resourceID || ',''' || mdirection || ''',''' || mtype || ''',' || quote_literal(msubj) || ',' || quote_literal(mbody) || ',' || mtimestamp || ')'; -+ END; -+ -+ UPDATE ~s SET count=count+1 where at=atdate and owner_id=ownerID and peer_name_id=peer_nameID and peer_server_id=peer_serverID; -+ IF NOT FOUND THEN -+ INSERT INTO ~s (owner_id, peer_name_id, peer_server_id, at, count) VALUES (ownerID, peer_nameID, peer_serverID, atdate, 1); -+ END IF; -+ RETURN 0; -+END; -+$$ LANGUAGE plpgsql; -+", [logmessage_name(VHost,Schema),UName,UName,UName,UName,SName,SName,RName,RName,Schema,escape_vhost(VHost),UName,UName,SName,RName,StName,StName]). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% SQL internals -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% like do_transaction/2 in mysql_conn.erl (changeset by Yariv Sadan ) -+sql_transaction_internal(DBRef, Fun) -> -+ case sql_query_internal(DBRef, ["BEGIN;"]) of -+ {updated, _} -> -+ case catch Fun() of -+ error = Err -> -+ rollback_internal(DBRef, Err); -+ {error, _} = Err -> -+ rollback_internal(DBRef, Err); -+ {'EXIT', _} = Err -> -+ rollback_internal(DBRef, Err); -+ Res -> -+ case sql_query_internal(DBRef, ["COMMIT;"]) of -+ {error, _} -> rollback_internal(DBRef, {commit_error}); -+ {updated, _} -> -+ case Res of -+ {atomic, _} -> Res; -+ _ -> {atomic, Res} -+ end -+ end -+ end; -+ {error, _} -> -+ {aborted, {begin_error}} -+ end. -+ -+% like rollback/2 in mysql_conn.erl (changeset by Yariv Sadan ) -+rollback_internal(DBRef, Reason) -> -+ Res = sql_query_internal(DBRef, ["ROLLBACK;"]), -+ {aborted, {Reason, {rollback_result, Res}}}. -+ -+sql_query_internal(DBRef, Query) -> -+ case sql_query_internal_silent(DBRef, Query) of -+ {error, undefined, Rez} -> -+ ?ERROR_MSG("Got undefined result: ~p while ~p", [Rez, lists:append(Query)]), -+ {error, undefined}; -+ {error, Error} -> -+ ?ERROR_MSG("Failed: ~p while ~p", [Error, lists:append(Query)]), -+ {error, Error}; -+ Rez -> Rez -+ end. -+ -+sql_query_internal_silent(DBRef, Query) -> -+ ?MYDEBUG("DOING: \"~s\"", [lists:append(Query)]), -+ % TODO: use pquery? -+ get_result(pgsql:squery(DBRef, Query)). -+ -+get_result({ok, ["CREATE TABLE"]}) -> -+ {updated, 1}; -+get_result({ok, ["DROP TABLE"]}) -> -+ {updated, 1}; -+get_result({ok, ["ALTER TABLE"]}) -> -+ {updated, 1}; -+get_result({ok,["DROP VIEW"]}) -> -+ {updated, 1}; -+get_result({ok,["DROP FUNCTION"]}) -> -+ {updated, 1}; -+get_result({ok, ["CREATE INDEX"]}) -> -+ {updated, 1}; -+get_result({ok, ["CREATE FUNCTION"]}) -> -+ {updated, 1}; -+get_result({ok, [{"SELECT", _Rows, Recs}]}) -> -+ {data, [list_to_tuple(Rec) || Rec <- Recs]}; -+get_result({ok, ["INSERT " ++ OIDN]}) -> -+ [_OID, N] = string:tokens(OIDN, " "), -+ {updated, list_to_integer(N)}; -+get_result({ok, ["DELETE " ++ N]}) -> -+ {updated, list_to_integer(N)}; -+get_result({ok, ["UPDATE " ++ N]}) -> -+ {updated, list_to_integer(N)}; -+get_result({ok, ["BEGIN"]}) -> -+ {updated, 1}; -+get_result({ok, ["LOCK TABLE"]}) -> -+ {updated, 1}; -+get_result({ok, ["ROLLBACK"]}) -> -+ {updated, 1}; -+get_result({ok, ["COMMIT"]}) -> -+ {updated, 1}; -+get_result({ok, ["SET"]}) -> -+ {updated, 1}; -+get_result({ok, [{error, Error}]}) -> -+ {error, Error}; -+get_result(Rez) -> -+ {error, undefined, Rez}. -+ ---- mod_logdb_mnesia_old.erl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ mod_logdb_mnesia_old.erl 2009-02-05 19:20:07.000000000 +0200 -@@ -0,0 +1,258 @@ -+%%%---------------------------------------------------------------------- -+%%% File : mod_logdb_mnesia_old.erl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : mod_logmnesia backend for mod_logdb (should be used only for copy_tables functionality) -+%%% Version : trunk -+%%% Id : $Id: mod_logdb_mnesia_old.erl 1169 2008-09-16 12:14:36Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-module(mod_logdb_mnesia_old). -+-author('o.palij@gmail.com'). -+ -+-include("ejabberd.hrl"). -+-include("jlib.hrl"). -+ -+-behaviour(gen_logdb). -+ -+-export([start/2, stop/1, -+ log_message/2, -+ rebuild_stats/1, -+ rebuild_stats_at/2, -+ rebuild_stats_at1/2, -+ delete_messages_by_user_at/3, delete_all_messages_by_user_at/3, delete_messages_at/2, -+ get_vhost_stats/1, get_vhost_stats_at/2, get_user_stats/2, get_user_messages_at/3, -+ get_dates/1, -+ get_users_settings/1, get_user_settings/2, set_user_settings/3, -+ drop_user/2]). -+ -+-record(stats, {user, server, table, count}). -+-record(msg, {to_user, to_server, to_resource, from_user, from_server, from_resource, id, type, subject, body, timestamp}). -+ -+tables_prefix() -> "messages_". -+% stats_table should not start with tables_prefix(VHost) ! -+% i.e. lists:prefix(tables_prefix(VHost), atom_to_list(stats_table())) must be /= true -+stats_table() -> list_to_atom("messages-stats"). -+% table name as atom from Date -+-define(ATABLE(Date), list_to_atom(tables_prefix() ++ Date)). -+-define(LTABLE(Date), tables_prefix() ++ Date). -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+start(_Opts, _VHost) -> -+ case mnesia:system_info(is_running) of -+ yes -> -+ ok = create_stats_table(), -+ {ok, ok}; -+ no -> -+ ?ERROR_MSG("Mnesia not running", []), -+ error; -+ Status -> -+ ?ERROR_MSG("Mnesia status: ~p", [Status]), -+ error -+ end. -+ -+stop(_VHost) -> -+ ok. -+ -+log_message(_VHost, _Msg) -> -+ error. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks (maintaince) -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+rebuild_stats(_VHost) -> -+ ok. -+ -+rebuild_stats_at(VHost, Date) -> -+ Table = ?LTABLE(Date), -+ {Time, Value}=timer:tc(?MODULE, rebuild_stats_at1, [VHost, Table]), -+ ?INFO_MSG("rebuild_stats_at ~p elapsed ~p sec: ~p~n", [Date, Time/1000000, Value]), -+ Value. -+rebuild_stats_at1(VHost, Table) -> -+ CFun = fun(Msg, Stats) -> -+ To = Msg#msg.to_user ++ "@" ++ Msg#msg.to_server, -+ Stats_to = if -+ Msg#msg.to_server == VHost -> -+ case lists:keysearch(To, 1, Stats) of -+ {value, {Who_to, Count_to}} -> -+ lists:keyreplace(To, 1, Stats, {Who_to, Count_to + 1}); -+ false -> -+ lists:append(Stats, [{To, 1}]) -+ end; -+ true -> -+ Stats -+ end, -+ From = Msg#msg.from_user ++ "@" ++ Msg#msg.from_server, -+ Stats_from = if -+ Msg#msg.from_server == VHost -> -+ case lists:keysearch(From, 1, Stats_to) of -+ {value, {Who_from, Count_from}} -> -+ lists:keyreplace(From, 1, Stats_to, {Who_from, Count_from + 1}); -+ false -> -+ lists:append(Stats_to, [{From, 1}]) -+ end; -+ true -> -+ Stats_to -+ end, -+ Stats_from -+ end, -+ DFun = fun(#stats{table=STable, server=Server} = Stat, _Acc) -+ when STable == Table, Server == VHost -> -+ mnesia:delete_object(stats_table(), Stat, write); -+ (_Stat, _Acc) -> ok -+ end, -+ case mnesia:transaction(fun() -> -+ mnesia:write_lock_table(list_to_atom(Table)), -+ mnesia:write_lock_table(stats_table()), -+ % Calc stats for VHost at Date -+ AStats = mnesia:foldl(CFun, [], list_to_atom(Table)), -+ % Delete all stats for VHost at Date -+ mnesia:foldl(DFun, [], stats_table()), -+ % Write new calc'ed stats -+ lists:foreach(fun({Who, Count}) -> -+ Jid = jlib:string_to_jid(Who), -+ JUser = Jid#jid.user, -+ WStat = #stats{user=JUser, server=VHost, table=Table, count=Count}, -+ mnesia:write(stats_table(), WStat, write) -+ end, AStats) -+ end) of -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to rebuild_stats_at for ~p at ~p: ~p", [VHost, Table, Reason]), -+ error; -+ {atomic, _} -> -+ ok -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks (delete) -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+delete_messages_by_user_at(_VHost, _Msgs, _Date) -> -+ error. -+ -+delete_all_messages_by_user_at(_User, _VHost, _Date) -> -+ error. -+ -+delete_messages_at(VHost, Date) -> -+ Table = list_to_atom(tables_prefix() ++ Date), -+ -+ DFun = fun(#msg{to_server=To_server, from_server=From_server}=Msg, _Acc) -+ when To_server == VHost; From_server == VHost -> -+ mnesia:delete_object(Table, Msg, write); -+ (_Msg, _Acc) -> ok -+ end, -+ -+ case mnesia:transaction(fun() -> -+ mnesia:foldl(DFun, [], Table) -+ end) of -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to delete_messages_at for ~p at ~p: ~p", [VHost, Date, Reason]), -+ error; -+ {atomic, _} -> -+ ok -+ end. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% gen_logdb callbacks (get) -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+get_vhost_stats(_VHost) -> -+ {error, "does not emplemented"}. -+ -+get_vhost_stats_at(VHost, Date) -> -+ Fun = fun() -> -+ Pat = #stats{user='$1', server=VHost, table=tables_prefix()++Date, count = '$2'}, -+ mnesia:select(stats_table(), [{Pat, [], [['$1', '$2']]}]) -+ end, -+ case mnesia:transaction(Fun) of -+ {atomic, Result} -> -+ RFun = fun([User, Count]) -> -+ {User, Count} -+ end, -+ {ok, lists:reverse(lists:keysort(2, lists:map(RFun, Result)))}; -+ {aborted, Reason} -> {error, Reason} -+ end. -+ -+get_user_stats(_User, _VHost) -> -+ {error, "does not emplemented"}. -+ -+get_user_messages_at(User, VHost, Date) -> -+ Table_name = tables_prefix() ++ Date, -+ case mnesia:transaction(fun() -> -+ Pat_to = #msg{to_user=User, to_server=VHost, _='_'}, -+ Pat_from = #msg{from_user=User, from_server=VHost, _='_'}, -+ mnesia:select(list_to_atom(Table_name), -+ [{Pat_to, [], ['$_']}, -+ {Pat_from, [], ['$_']}]) -+ end) of -+ {atomic, Result} -> -+ Msgs = lists:map(fun(#msg{to_user=To_user, to_server=To_server, to_resource=To_res, -+ from_user=From_user, from_server=From_server, from_resource=From_res, -+ type=Type, -+ subject=Subj, -+ body=Body, timestamp=Timestamp} = _Msg) -> -+ Subject = case Subj of -+ "None" -> ""; -+ _ -> Subj -+ end, -+ {msg, To_user, To_server, To_res, From_user, From_server, From_res, Type, Subject, Body, Timestamp} -+ end, Result), -+ {ok, Msgs}; -+ {aborted, Reason} -> -+ {error, Reason} -+ end. -+ -+get_dates(_VHost) -> -+ Tables = mnesia:system_info(tables), -+ MessagesTables = -+ lists:filter(fun(Table) -> -+ lists:prefix(tables_prefix(), atom_to_list(Table)) -+ end, -+ Tables), -+ lists:map(fun(Table) -> -+ lists:sublist(atom_to_list(Table), -+ length(tables_prefix())+1, -+ length(atom_to_list(Table))) -+ end, -+ MessagesTables). -+ -+get_users_settings(_VHost) -> -+ {ok, []}. -+get_user_settings(_User, _VHost) -> -+ {ok, []}. -+set_user_settings(_User, _VHost, _Set) -> -+ ok. -+drop_user(_User, _VHost) -> -+ ok. -+ -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% -+% internal -+% -+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -+% called from db_logon/2 -+create_stats_table() -> -+ SName = stats_table(), -+ case mnesia:create_table(SName, -+ [{disc_only_copies, [node()]}, -+ {type, bag}, -+ {attributes, record_info(fields, stats)}, -+ {record_name, stats} -+ ]) of -+ {atomic, ok} -> -+ ?INFO_MSG("Created stats table", []), -+ ok; -+ {aborted, {already_exists, _}} -> -+ ok; -+ {aborted, Reason} -> -+ ?ERROR_MSG("Failed to create stats table: ~p", [Reason]), -+ error -+ end. ---- gen_logdb.erl.orig 2009-02-05 19:21:29.000000000 +0200 -+++ gen_logdb.erl 2009-02-05 19:19:39.000000000 +0200 -@@ -0,0 +1,164 @@ -+%%%---------------------------------------------------------------------- -+%%% File : gen_logdb.erl -+%%% Author : Oleg Palij (mailto,xmpp:o.palij@gmail.com) -+%%% Purpose : Describes generic behaviour for mod_logdb backends. -+%%% Version : trunk -+%%% Id : $Id: gen_logdb.erl 1169 2008-09-16 12:14:36Z malik $ -+%%% Url : http://www.dp.uz.gov.ua/o.palij/mod_logdb/ -+%%%---------------------------------------------------------------------- -+ -+-module(gen_logdb). -+-author('o.palij@gmail.com'). -+ -+-export([behaviour_info/1]). -+ -+behaviour_info(callbacks) -> -+ [ -+ % called from handle_info(start, _) -+ % it should logon database and return reference to started instance -+ % start(VHost, Opts) -> {ok, SPid} | error -+ % Options - list of options to connect to db -+ % Types: Options = list() -> [] | -+ % [{user, "logdb"}, -+ % {pass, "1234"}, -+ % {db, "logdb"}] | ... -+ % VHost = list() -> "jabber.example.org" -+ {start, 2}, -+ -+ % called from cleanup/1 -+ % it should logoff database and do cleanup -+ % stop(VHost) -+ % Types: VHost = list() -> "jabber.example.org" -+ {stop, 1}, -+ -+ % called from handle_call({addlog, _}, _, _) -+ % it should log messages to database -+ % log_message(VHost, Msg) -> ok | error -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ % Msg = record() -> #msg -+ {log_message, 2}, -+ -+ % called from ejabberdctl rebuild_stats -+ % it should rebuild stats table (if used) for vhost -+ % rebuild_stats(VHost) -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ {rebuild_stats, 1}, -+ -+ % it should rebuild stats table (if used) for vhost at Date -+ % rebuild_stats_at(VHost, Date) -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ % Date = list() -> "2007-02-12" -+ {rebuild_stats_at, 2}, -+ -+ % called from user_messages_at_parse_query/5 -+ % it should delete selected user messages at date -+ % delete_messages_by_user_at(VHost, Msgs, Date) -> ok | error -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ % Msgs = list() -> [ #msg1, msg2, ... ] -+ % Date = list() -> "2007-02-12" -+ {delete_messages_by_user_at, 3}, -+ -+ % called from user_messages_parse_query/4 | vhost_messages_at_parse_query/4 -+ % it should delete all user messages at date -+ % delete_all_messages_by_user_at(User, VHost, Date) -> ok | error -+ % Types: -+ % User = list() -> "admin" -+ % VHost = list() -> "jabber.example.org" -+ % Date = list() -> "2007-02-12" -+ {delete_all_messages_by_user_at, 3}, -+ -+ % called from vhost_messages_parse_query/3 -+ % it should delete messages for vhost at date and update stats -+ % delete_messages_at(VHost, Date) -> ok | error -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ % Date = list() -> "2007-02-12" -+ {delete_messages_at, 2}, -+ -+ % called from ejabberd_web_admin:vhost_messages_stats/3 -+ % it should return sorted list of count of messages by dates for vhost -+ % get_vhost_stats(VHost) -> {ok, [{Date1, Msgs_count1}, {Date2, Msgs_count2}, ... ]} | -+ % {error, Reason} -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ % DateN = list() -> "2007-02-12" -+ % Msgs_countN = number() -> 241 -+ {get_vhost_stats, 1}, -+ -+ % called from ejabberd_web_admin:vhost_messages_stats_at/4 -+ % it should return sorted list of count of messages by users at date for vhost -+ % get_vhost_stats_at(VHost, Date) -> {ok, [{User1, Msgs_count1}, {User2, Msgs_count2}, ....]} | -+ % {error, Reason} -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ % Date = list() -> "2007-02-12" -+ % UserN = list() -> "admin" -+ % Msgs_countN = number() -> 241 -+ {get_vhost_stats_at, 2}, -+ -+ % called from ejabberd_web_admin:user_messages_stats/4 -+ % it should return sorted list of count of messages by date for user at vhost -+ % get_user_stats(User, VHost) -> {ok, [{Date1, Msgs_count1}, {Date2, Msgs_count2}, ...]} | -+ % {error, Reason} -+ % Types: -+ % User = list() -> "admin" -+ % VHost = list() -> "jabber.example.org" -+ % DateN = list() -> "2007-02-12" -+ % Msgs_countN = number() -> 241 -+ {get_user_stats, 2}, -+ -+ % called from ejabberd_web_admin:user_messages_stats_at/5 -+ % it should return all user messages at date -+ % get_user_messages_at(User, VHost, Date) -> {ok, Msgs} | {error, Reason} -+ % Types: -+ % User = list() -> "admin" -+ % VHost = list() -> "jabber.example.org" -+ % Date = list() -> "2007-02-12" -+ % Msgs = list() -> [ #msg1, msg2, ... ] -+ {get_user_messages_at, 3}, -+ -+ % called from many places -+ % it should return list of dates for vhost -+ % get_dates(VHost) -> [Date1, Date2, ... ] -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ % DateN = list() -> "2007-02-12" -+ {get_dates, 1}, -+ -+ % called from start -+ % it should return list with users settings for VHost in db -+ % get_users_settings(VHost) -> [#user_settings1, #user_settings2, ... ] | error -+ % Types: -+ % VHost = list() -> "jabber.example.org" -+ {get_users_settings, 1}, -+ -+ % called from many places -+ % it should return User settings at VHost from db -+ % get_user_settings(User, VHost) -> error | {ok, #user_settings} -+ % Types: -+ % User = list() -> "admin" -+ % VHost = list() -> "jabber.example.org" -+ {get_user_settings, 2}, -+ -+ % called from web admin -+ % it should set User settings at VHost -+ % set_user_settings(User, VHost, #user_settings) -> ok | error -+ % Types: -+ % User = list() -> "admin" -+ % VHost = list() -> "jabber.example.org" -+ {set_user_settings, 3}, -+ -+ % called from remove_user (ejabberd hook) -+ % it should remove user messages and settings at VHost -+ % drop_user(User, VHost) -> ok | error -+ % Types: -+ % User = list() -> "admin" -+ % VHost = list() -> "jabber.example.org" -+ {drop_user, 2} -+ ]; -+behaviour_info(_) -> -+ undefined. ---- web/ejabberd_web_admin-2.0.3.erl 2009-02-03 08:27:39.000000000 +0200 -+++ web/ejabberd_web_admin.erl 2009-02-03 08:40:57.000000000 +0200 -@@ -1514,25 +1514,31 @@ - - - user_parse_query(User, Server, Query) -> -- case lists:keysearch("chpassword", 1, Query) of -- {value, _} -> -- case lists:keysearch("password", 1, Query) of -- {value, {_, undefined}} -> -- error; -- {value, {_, Password}} -> -- ejabberd_auth:set_password(User, Server, Password), -- ok; -- _ -> -- error -- end; -- _ -> -- case lists:keysearch("removeuser", 1, Query) of -- {value, _} -> -- ejabberd_auth:remove_user(User, Server), -- ok; -- false -> -- nothing -- end -+ lists:foldl(fun({Action, Value}, Acc) when Acc == nothing -> -+ user_parse_query1(Action, User, Server, Query); -+ ({Action, Value}, Acc) -> -+ Acc -+ end, nothing, Query). -+ -+user_parse_query1("password", User, Server, Query) -> -+ nothing; -+user_parse_query1("chpassword", User, Server, Query) -> -+ case lists:keysearch("password", 1, Query) of -+ {value, {_, undefined}} -> -+ error; -+ {value, {_, Password}} -> -+ ejabberd_auth:set_password(User, Server, Password), -+ ok; -+ _ -> -+ error -+ end; -+user_parse_query1("removeuser", User, Server, Query) -> -+ ejabberd_auth:remove_user(User, Server), -+ ok; -+user_parse_query1(Action, User, Server, Query) -> -+ case ejabberd_hooks:run_fold(webadmin_user_parse_query, Server, [], [Action, User, Server, Query]) of -+ [] -> nothing; -+ Res -> Res - end. - - ---- mod_muc/mod_muc_room-2.0.3.erl 2009-02-03 08:27:59.000000000 +0200 -+++ mod_muc/mod_muc_room.erl 2009-02-03 08:37:26.000000000 +0200 -@@ -695,6 +695,12 @@ - handle_sync_event({change_config, Config}, _From, StateName, StateData) -> - {result, [], NSD} = change_config(Config, StateData), - {reply, {ok, NSD#state.config}, StateName, NSD}; -+handle_sync_event({get_jid_nick, Jid}, _From, StateName, StateData) -> -+ R = case ?DICT:find(jlib:jid_tolower(Jid), StateData#state.users) of -+ error -> []; -+ {ok, {user, _, Nick, _, _}} -> Nick -+ end, -+ {reply, R, StateName, StateData}; - handle_sync_event(_Event, _From, StateName, StateData) -> - Reply = ok, - {reply, Reply, StateName, StateData}. ---- msgs/uk-2.0.3.msg 2009-01-14 11:54:15.000000000 +0200 -+++ msgs/uk.msg 2009-02-03 08:26:20.000000000 +0200 -@@ -388,6 +388,35 @@ - % mod_offline_odbc.erl - {"Your contact offline message queue is full. The message has been discarded.", "Черга повідомлень, що не були доÑтавлені, переповнена. ÐŸÐ¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ Ð½Ðµ було збережено."}. - -+% mod_logdb -+{"Users Messages", "ÐŸÐ¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ ÐºÐ¾Ñ€Ð¸Ñтувачів"}. -+{"Date", "Дата"}. -+{"Count", "КількіÑÑ‚ÑŒ"}. -+{"Logged messages for ", "Збережені Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ Ð´Ð»Ñ "}. -+{" at ", " за "}. -+{"No logged messages for ", "ВідÑутні Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ Ð´Ð»Ñ "}. -+{"Date, Time", "Дата, ЧаÑ"}. -+{"Direction: Jid", "ÐапрÑмок: Jid"}. -+{"Subject", "Тема"}. -+{"Body", "ТекÑÑ‚"}. -+{"Messages", "ПовідомленнÑ"}. -+{"Filter Selected", "Відфільтрувати виділені"}. -+{"Do Not Log Messages", "Ðе зберігати повідомленнÑ"}. -+{"Log Messages", "Зберігати повідомленнÑ"}. -+{"Messages logging engine", "СиÑтема Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½ÑŒ"}. -+{"Default", "За замовчуваннÑм"}. -+{"Set logging preferences", "Вкажіть Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÑƒÐ²Ð°Ð½Ð½Ñ Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½ÑŒ"}. -+{"Messages logging engine users", "КориÑтувачі ÑиÑтеми Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½ÑŒ"}. -+{"Messages logging engine settings", "ÐÐ°Ð»Ð°Ð³Ð¾Ð´Ð¶ÑƒÐ²Ð°Ð½Ð½Ñ ÑиÑтеми Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½ÑŒ"}. -+{"Set run-time settings", "Вкажіть поточні налагоджуваннÑ"}. -+{"Groupchat messages logging", "Ð—Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½ÑŒ типу groupchat"}. -+{"Jids/Domains to ignore", "Ігнорувати наÑтупні jids/домени"}. -+{"Purge messages older than (days)", "ВидалÑти Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ Ñтаріші ніж (дні)"}. -+{"Poll users settings (seconds)", "Оновлювати Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÑƒÐ²Ð°Ð½Ð½Ñ ÐºÐ¾Ñ€Ð¸Ñтувачів кожні (Ñекунд)"}. -+{"Drop", "ВидалÑти"}. -+{"Do not drop", "Ðе видалÑти"}. -+{"Drop messages on user removal", "ВидалÑти Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð²Ð¸Ð´Ð°Ð»ÐµÐ½Ð½Ñ ÐºÐ¾Ñ€Ð¸Ñтувача"}. -+ - % Local Variables: - % mode: erlang - % End: ---- msgs/ru-2.0.3.msg 2009-01-14 11:54:15.000000000 +0200 -+++ msgs/ru.msg 2009-02-03 08:25:31.000000000 +0200 -@@ -388,6 +388,35 @@ - % mod_offline_odbc.erl - {"Your contact offline message queue is full. The message has been discarded.", "Очередь недоÑтавленных Ñообщений Вашего адреÑата переполнена. Сообщение не было Ñохранено."}. - -+% mod_logdb.erl -+{"Users Messages", "Ð¡Ð¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»ÐµÐ¹"}. -+{"Date", "Дата"}. -+{"Count", "КоличеÑтво"}. -+{"Logged messages for ", "Сохранённые cÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð´Ð»Ñ "}. -+{" at ", " за "}. -+{"No logged messages for ", "ОтÑутÑтвуют ÑÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð´Ð»Ñ "}. -+{"Date, Time", "Дата, ВремÑ"}. -+{"Direction: Jid", "Ðаправление: Jid"}. -+{"Subject", "Тема"}. -+{"Body", "ТекÑÑ‚"}. -+{"Messages", "СообщениÑ"}. -+{"Filter Selected", "Отфильтровать выделенные"}. -+{"Do Not Log Messages", "Ðе ÑохранÑÑ‚ÑŒ ÑообщениÑ"}. -+{"Log Messages", "СохранÑÑ‚ÑŒ ÑообщениÑ"}. -+{"Messages logging engine", "СиÑтема Ð»Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ñообщений"}. -+{"Default", "По умолчанию"}. -+{"Set logging preferences", "Задайте наÑтройки логированиÑ"}. -+{"Messages logging engine users", "Пользователи ÑиÑтемы Ð»Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ñообщений"}. -+{"Messages logging engine settings", "ÐаÑтройки ÑиÑтемы Ð»Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ñообщений"}. -+{"Set run-time settings", "Задайте текущие наÑтройки"}. -+{"Groupchat messages logging", "Логирование Ñообщений типа groupchat"}. -+{"Jids/Domains to ignore", "Игнорировать Ñледующие jids/домены"}. -+{"Purge messages older than (days)", "УдалÑÑ‚ÑŒ ÑÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ñтарее чем (дни)"}. -+{"Poll users settings (seconds)", "ОбновлÑÑ‚ÑŒ наÑтройки пользователей через (Ñекунд)"}. -+{"Drop", "УдалÑÑ‚ÑŒ"}. -+{"Do not drop", "Ðе удалÑÑ‚ÑŒ"}. -+{"Drop messages on user removal", "УдалÑÑ‚ÑŒ ÑÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð¿Ñ€Ð¸ удалении пользователÑ"}. -+ - % Local Variables: - % mode: erlang - % End: ---- msgs/pl-2.0.3.msg 2009-01-14 11:54:15.000000000 +0200 -+++ msgs/pl.msg 2009-02-03 08:24:33.000000000 +0200 -@@ -408,6 +408,31 @@ - % mod_offline.erl - {"Your contact offline message queue is full. The message has been discarded.", "Twoja kolejka wiadomoci offline jest peÅ‚na. Wiadomoć zostaÅ‚a odrzucona."}. - -+% mod_logdb -+{"Users Messages", "WiadomoÅ›ci użytkownika"}. -+{"Date", "Data"}. -+{"Count", "Liczba"}. -+{"Logged messages for ", "Zapisane wiadomoÅ›ci dla "}. -+{" at ", " o "}. -+{"No logged messages for ", "Brak zapisanych wiadomoÅ›ci dla "}. -+{"Date, Time", "Data, Godzina"}. -+{"Direction: Jid", "Kierunek: Jid"}. -+{"Subject", "Temat"}. -+{"Body", "Treść"}. -+{"Messages","WiadomoÅ›ci"}. -+{"Filter Selected", "Odfiltruj zaznaczone"}. -+{"Do Not Log Messages", "Nie zapisuj wiadomoÅ›ci"}. -+{"Log Messages", "Zapisuj wiadomoÅ›ci"}. -+{"Messages logging engine", "System zapisywania historii rozmów"}. -+{"Default", "DomyÅ›lne"}. -+{"Set logging preferences", "Ustaw preferencje zapisywania"}. -+{"Messages logging engine settings", "Ustawienia systemu logowania"}. -+{"Set run-time settings", "Zapisz ustawienia systemu logowania"}. -+{"Groupchat messages logging", "Zapisywanie rozmów z konferencji"}. -+{"Jids/Domains to ignore", "JID/Domena która ma być ignorowana"}. -+{"Purge messages older than (days)", "UsuÅ„ wiadomoÅ›ci starsze niż (w dniach)"}. -+{"Poll users settings (seconds)", "Czas aktualizacji preferencji użytkowników (sekundy)"}. -+ - % Local Variables: - % mode: erlang - % End: ---- msgs/nl-2.0.3.msg 2009-01-14 11:54:15.000000000 +0200 -+++ msgs/nl.msg 1970-01-01 03:00:00.000000000 +0300 -@@ -379,6 +379,19 @@ - % mod_proxy65/mod_proxy65_service.erl - {"ejabberd SOCKS5 Bytestreams module", "ejabberd SOCKS5 Bytestreams module"}. - -+% mod_logdb -+{"Users Messages", "Gebruikersberichten"}. -+{"Date", "Datum"}. -+{"Count", "Aantal"}. -+{"Logged messages for ", "Gelogde berichten van "}. -+{" at ", " op "}. -+{"No logged messages for ", "Geen gelogde berichten van "}. -+{"Date, Time", "Datum en tijd"}. -+{"Direction: Jid", "Richting: Jabber ID"}. -+{"Subject", "Onderwerp"}. -+{"Body", "Berichtveld"}. -+{"Messages", "Berichten"}. -+ - % Local Variables: - % mode: erlang - % End: ---- ./mod_roster-2.0.3.erl 2009-02-03 08:28:12.000000000 +0200 -+++ mod_roster.erl 2009-02-03 08:32:14.000000000 +0200 -@@ -48,7 +48,7 @@ - -include("mod_roster.hrl"). - -include("web/ejabberd_http.hrl"). - -include("web/ejabberd_web_admin.hrl"). -- -+-include("mod_logdb.hrl"). - - start(Host, Opts) -> - IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue), -@@ -829,6 +829,14 @@ - Res = user_roster_parse_query(User, Server, Items1, Query), - Items = mnesia:dirty_index_read(roster, US, #roster.us), - SItems = lists:sort(Items), -+ -+ Settings = case gen_mod:is_loaded(Server, mod_logdb) of -+ true -> -+ mod_logdb:get_user_settings(User, Server); -+ false -> -+ [] -+ end, -+ - FItems = - case SItems of - [] -> -@@ -876,7 +884,33 @@ - [?INPUTT("submit", - "remove" ++ - ejabberd_web_admin:term_to_id(R#roster.jid), -- "Remove")])]) -+ "Remove")]), -+ case gen_mod:is_loaded(Server, mod_logdb) of -+ true -> -+ Peer = jlib:jid_to_string(R#roster.jid), -+ A = lists:member(Peer, Settings#user_settings.dolog_list), -+ B = lists:member(Peer, Settings#user_settings.donotlog_list), -+ {Name, Value} = -+ if -+ A -> -+ {"donotlog", "Do Not Log Messages"}; -+ B -> -+ {"dolog", "Log Messages"}; -+ Settings#user_settings.dolog_default == true -> -+ {"donotlog", "Do Not Log Messages"}; -+ Settings#user_settings.dolog_default == false -> -+ {"dolog", "Log Messages"} -+ end, -+ -+ ?XAE("td", [{"class", "valign"}], -+ [?INPUTT("submit", -+ Name ++ -+ ejabberd_web_admin:term_to_id(R#roster.jid), -+ Value)]); -+ false -> -+ ?X([]) -+ end -+ ]) - end, SItems))])] - end, - [?XC("h1", ?T("Roster of ") ++ us_to_list(US))] ++ -@@ -958,11 +992,42 @@ - {"subscription", "remove"}], - []}]}}), - throw(submitted); -- false -> -- ok -- end -- -- end -+ false -> -+ case lists:keysearch( -+ "donotlog" ++ ejabberd_web_admin:term_to_id(JID), 1, Query) of -+ {value, _} -> -+ Peer = jlib:jid_to_string(JID), -+ Settings = mod_logdb:get_user_settings(User, Server), -+ DNLL = case lists:member(Peer, Settings#user_settings.donotlog_list) of -+ false -> lists:append(Settings#user_settings.donotlog_list, [Peer]); -+ true -> Settings#user_settings.donotlog_list -+ end, -+ DLL = lists:delete(jlib:jid_to_string(JID), Settings#user_settings.dolog_list), -+ Sett = Settings#user_settings{donotlog_list=DNLL, dolog_list=DLL}, -+ % TODO: check returned value -+ ok = mod_logdb:set_user_settings(User, Server, Sett), -+ throw(nothing); -+ false -> -+ case lists:keysearch( -+ "dolog" ++ ejabberd_web_admin:term_to_id(JID), 1, Query) of -+ {value, _} -> -+ Peer = jlib:jid_to_string(JID), -+ Settings = mod_logdb:get_user_settings(User, Server), -+ DLL = case lists:member(Peer, Settings#user_settings.dolog_list) of -+ false -> lists:append(Settings#user_settings.dolog_list, [Peer]); -+ true -> Settings#user_settings.dolog_list -+ end, -+ DNLL = lists:delete(jlib:jid_to_string(JID), Settings#user_settings.donotlog_list), -+ Sett = Settings#user_settings{donotlog_list=DNLL, dolog_list=DLL}, -+ % TODO: check returned value -+ ok = mod_logdb:set_user_settings(User, Server, Sett), -+ throw(nothing); -+ false -> -+ ok -+ end % dolog -+ end % donotlog -+ end % remove -+ end % validate - end, Items), - nothing. - ---- ./mod_roster_odbc-2.0.3.erl 2009-02-03 08:28:26.000000000 +0200 -+++ mod_roster_odbc.erl 2009-02-03 08:47:04.000000000 +0200 -@@ -48,7 +48,7 @@ - -include("mod_roster.hrl"). - -include("web/ejabberd_http.hrl"). - -include("web/ejabberd_web_admin.hrl"). -- -+-include("mod_logdb.hrl"). - - start(Host, Opts) -> - IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue), -@@ -937,6 +937,14 @@ - Res = user_roster_parse_query(User, Server, Items1, Query), - Items = get_roster(LUser, LServer), - SItems = lists:sort(Items), -+ -+ Settings = case gen_mod:is_loaded(Server, mod_logdb) of -+ true -> -+ mod_logdb:get_user_settings(User, Server); -+ false -> -+ [] -+ end, -+ - FItems = - case SItems of - [] -> -@@ -984,7 +992,33 @@ - [?INPUTT("submit", - "remove" ++ - ejabberd_web_admin:term_to_id(R#roster.jid), -- "Remove")])]) -+ "Remove")]), -+ case gen_mod:is_loaded(Server, mod_logdb) of -+ true -> -+ Peer = jlib:jid_to_string(R#roster.jid), -+ A = lists:member(Peer, Settings#user_settings.dolog_list), -+ B = lists:member(Peer, Settings#user_settings.donotlog_list), -+ {Name, Value} = -+ if -+ A -> -+ {"donotlog", "Do Not Log Messages"}; -+ B -> -+ {"dolog", "Log Messages"}; -+ Settings#user_settings.dolog_default == true -> -+ {"donotlog", "Do Not Log Messages"}; -+ Settings#user_settings.dolog_default == false -> -+ {"dolog", "Log Messages"} -+ end, -+ -+ ?XAE("td", [{"class", "valign"}], -+ [?INPUTT("submit", -+ Name ++ -+ ejabberd_web_admin:term_to_id(R#roster.jid), -+ Value)]); -+ false -> -+ ?X([]) -+ end -+ ]) - end, SItems))])] - end, - [?XC("h1", ?T("Roster of ") ++ us_to_list(US))] ++ -@@ -1066,11 +1100,42 @@ - {"subscription", "remove"}], - []}]}}), - throw(submitted); -- false -> -- ok -- end -- -- end -+ false -> -+ case lists:keysearch( -+ "donotlog" ++ ejabberd_web_admin:term_to_id(JID), 1, Query) of -+ {value, _} -> -+ Peer = jlib:jid_to_string(JID), -+ Settings = mod_logdb:get_user_settings(User, Server), -+ DNLL = case lists:member(Peer, Settings#user_settings.donotlog_list) of -+ false -> lists:append(Settings#user_settings.donotlog_list, [Peer]); -+ true -> Settings#user_settings.donotlog_list -+ end, -+ DLL = lists:delete(jlib:jid_to_string(JID), Settings#user_settings.dolog_list), -+ Sett = Settings#user_settings{donotlog_list=DNLL, dolog_list=DLL}, -+ % TODO: check returned value -+ ok = mod_logdb:set_user_settings(User, Server, Sett), -+ throw(nothing); -+ false -> -+ case lists:keysearch( -+ "dolog" ++ ejabberd_web_admin:term_to_id(JID), 1, Query) of -+ {value, _} -> -+ Peer = jlib:jid_to_string(JID), -+ Settings = mod_logdb:get_user_settings(User, Server), -+ DLL = case lists:member(Peer, Settings#user_settings.dolog_list) of -+ false -> lists:append(Settings#user_settings.dolog_list, [Peer]); -+ true -> Settings#user_settings.dolog_list -+ end, -+ DNLL = lists:delete(jlib:jid_to_string(JID), Settings#user_settings.donotlog_list), -+ Sett = Settings#user_settings{donotlog_list=DNLL, dolog_list=DLL}, -+ % TODO: check returned value -+ ok = mod_logdb:set_user_settings(User, Server, Sett), -+ throw(nothing); -+ false -> -+ ok -+ end % dolog -+ end % donotlog -+ end % remove -+ end % validate - end, Items), - nothing. - diff --git a/jorge/mod_logdb/patch-src-mod_logdb-disable_ejabberd_ctl.diff b/jorge/mod_logdb/patch-src-mod_logdb-disable_ejabberd_ctl.diff deleted file mode 100644 index 7b9b902..0000000 --- a/jorge/mod_logdb/patch-src-mod_logdb-disable_ejabberd_ctl.diff +++ /dev/null @@ -1,65 +0,0 @@ -Index: mod_logdb.erl -=================================================================== ---- mod_logdb.erl (revision 1273) -+++ mod_logdb.erl (working copy) -@@ -126,7 +126,7 @@ - purge_older_days=gen_mod:get_opt(purge_older_days, Opts, never), - poll_users_settings=PollUsersSettings}}. - --cleanup(#state{vhost=VHost} = State) -> -+cleanup(#state{vhost=VHost} = _State) -> - ?MYDEBUG("Stopping ~s for ~p", [?MODULE, VHost]), - - %ets:delete(ets_settings_table(VHost)), -@@ -153,14 +153,14 @@ - - ?MYDEBUG("Removed hooks for ~p", [VHost]), - -- ejabberd_ctl:unregister_commands(VHost, [{"rebuild_stats", "rebuild mod_logdb module stats for vhost"}], ?MODULE, rebuild_stats), -- Supported_backends = lists:flatmap(fun({Backend, _Opts}) -> -- [atom_to_list(Backend), " "] -- end, State#state.dbs), -- ejabberd_ctl:unregister_commands( -- VHost, -- [{"copy_messages backend", "copy messages from backend to current backend. backends could be: " ++ Supported_backends }], -- ?MODULE, copy_messages_ctl), -+ %ejabberd_ctl:unregister_commands(VHost, [{"rebuild_stats", "rebuild mod_logdb module stats for vhost"}], ?MODULE, rebuild_stats), -+ %Supported_backends = lists:flatmap(fun({Backend, _Opts}) -> -+ % [atom_to_list(Backend), " "] -+ % end, State#state.dbs), -+ %ejabberd_ctl:unregister_commands( -+ % VHost, -+ % [{"copy_messages backend", "copy messages from backend to current backend. backends could be: " ++ Supported_backends }], -+ % ?MODULE, copy_messages_ctl), - ?MYDEBUG("Unregistered commands for ~p", [VHost]). - - stop(VHost) -> -@@ -388,17 +388,17 @@ - - ?MYDEBUG("Added hooks for ~p", [VHost]), - -- ejabberd_ctl:register_commands( -- VHost, -- [{"rebuild_stats", "rebuild mod_logdb module stats for vhost"}], -- ?MODULE, rebuild_stats), -- Supported_backends = lists:flatmap(fun({Backend, _Opts}) -> -- [atom_to_list(Backend), " "] -- end, State#state.dbs), -- ejabberd_ctl:register_commands( -- VHost, -- [{"copy_messages backend", "copy messages from backend to current backend. backends could be: " ++ Supported_backends }], -- ?MODULE, copy_messages_ctl), -+ %ejabberd_ctl:register_commands( -+ % VHost, -+ % [{"rebuild_stats", "rebuild mod_logdb module stats for vhost"}], -+ % ?MODULE, rebuild_stats), -+ %Supported_backends = lists:flatmap(fun({Backend, _Opts}) -> -+ % [atom_to_list(Backend), " "] -+ % end, State#state.dbs), -+ %ejabberd_ctl:register_commands( -+ % VHost, -+ % [{"copy_messages backend", "copy messages from backend to current backend. backends could be: " ++ Supported_backends }], -+ % ?MODULE, copy_messages_ctl), - ?MYDEBUG("Registered commands for ~p", [VHost]), - - NewState=State#state{monref = MonRef, backendPid=SPid, purgeRef=TrefPurge, pollRef=TrefPoll}, diff --git a/jorge/mod_logdb/readme.txt b/jorge/mod_logdb/readme.txt deleted file mode 100644 index 5bcc318..0000000 --- a/jorge/mod_logdb/readme.txt +++ /dev/null @@ -1,48 +0,0 @@ -mod_logdb by Oleg Palij ------------------------ - -*NOTE* - Jorge is compatible only with the distributed mod_logdb. Please follow instruction below carefully. - -Instalation instruction: - -1) Grab ejabberd from SVN (Tested with Revision: 1868, but probably will work with any newer) or ejabberd 2.x -2) Patch mysql erlang driver with userflags patch -3) Patch sources of ejabberd using "patch" tool - (f.e: patch -p0 < patch-src-mod_logdb_svn) -4) Setup mysql5 database (dbname, username, etc...). - Db schema will be automaticaly setup during mod_logdb startup. -5) Edit config of your ejabberd server by adding following lines into modules section: -6) If you are using mysql5 backend with procedural language *you must patch* mysql driver with provided patch: userflags.diff, and add user priviledges for creating views (CREATE VIEW) - -{modules, [ - ... - {mod_logdb, - [{vhosts, [{"your_xmpp_server", mysql5}]}, - {dbs, [{mysql5, [{user, "db_username"}, - {password, "db_password"}, - {server, "ip_of_the_db_server"}, - {port, 3306}, - {db, "db_name"} - ] - }]}, - {groupchat, none}, - {purge_older_days, never}, - {ignore_jids, ["example@jid.pl", "example2@jid.pl"]}, - {dolog_default, false} - ] - }, - ... -]}. - -And for ad-hoc commands, add on the top of the config file: - -{access, mod_logdb, [{allow, all}]}. -{access, mod_logdb_admin, [{allow, admin}]}. - -7) Restart the server -8) Have fun - -For further info consult mod_logdb manual. - -Note for admins who use clustered setup: you need to install mod_logdb on each ejabberd node. -Multiple mod_logdb sessions can share database access without any problems. diff --git a/jorge/my_links.php b/jorge/my_links.php deleted file mode 100644 index ed10187..0000000 --- a/jorge/my_links.php +++ /dev/null @@ -1,193 +0,0 @@ -decrypt_url($_GET[a]) === true) { - - $variables[tslice] = $enc->tslice; - $variables[peer_name_id] = $enc->peer_name_id; - $variables[peer_server_id] = $enc->peer_server_id; - $variables[lnk] = $enc->lnk; - $variables[linktag] = $enc->linktag; - $variables[strt] = $enc->strt; - $variables[ismylink] = $enc->ismylink; - - } - else { - unset($variables); - - } - -} - -if ($del === "t") { - - if ($db->del_mylink($link_id) === true) { - - $html->status_message($my_links_removed[$lang]); - - // recount number of links - $db->get_mylinks_count(); - $my_links_count = $db->result->cnt; - - } - - else { - - $html->alert_message($oper_fail[$lang]); - - } - -} - - -if ($tigger === $my_links_commit[$lang]) { - - if ($enc->decrypt_url($_POST[hidden_field]) === true) { - - $peer_name_id = $enc->peer_name_id; - $peer_server_id = $enc->peer_server_id; - $datat = $enc->tslice; - $lnk = $enc->lnk; - $strt = $enc->strt; - $linktag = $enc->linktag; - $link = $lnk."&start=$strt#$linktag"; - if ($desc === $my_links_optional[$lang]) { - - $desc = $my_links_none[$lang]; - - } - - $desc = substr($desc,0,120); - if($db->add_mylink($peer_name_id,$peer_server_id,$datat,$link,$desc) === true) { - - $html->status_message($my_links_added[$lang].' -
    '.$my_links_back[$lang].''); - - // recount number of links - $db->get_mylinks_count(); - $my_links_count = $db->result->cnt; - - } - else{ - - $html->alert_message($oper_fail[$lang]); - - } - - } - -} - -if ($variables[ismylink] === "1") { - - $db->get_server_name($enc->peer_server_id); - $sname = $db->result->server_name; - $db->get_user_name($enc->peer_name_id); - $uname = $db->result->username; - $nickname=query_nick_name($ejabberd_roster,$uname,$sname); - $jid=''.$uname.'@'.$sname.''; - $hidden_fields = $enc->crypt_url("tslice=$enc->tslice&peer_name_id=$variables[peer_name_id]&peer_server_id=$variables[peer_server_id]&lnk=$variables[lnk]&strt=$variables[strt]&linktag=$variables[linktag]"); - if (!$nickname) { - - $nickname = $not_in_r[$lang]; - $jid = $sname; - - } - $html->set_body(' -
    - '.$my_links_save_d[$lang].'
    - - - - - - - -
    '.$my_links_chat[$lang].'   - '.cut_nick($nickname).' ('.htmlspecialchars($jid).')
          -
    -



    - '); - -} - -$html->set_overview('

    '.$my_links_desc_m[$lang].'

    '.$my_links_desc_e[$lang].''); - -if ($my_links_count === "0") { - - $html->status_message($my_links_no_links[$lang]); - - } - - else { - - $html->set_body(' -
    - - - - '); - $db->get_mylink(); - $result = $db->result; - foreach ($result as $entry) { - - $db->get_user_name($entry[peer_name_id]); - $peer_name = $db->result->username; - $db->get_server_name($entry[peer_server_id]); - $peer_server = $db->result->server_name; - $nickname=query_nick_name($ejabberd_roster,$peer_name,$peer_server); - $desc = htmlspecialchars($entry[description]); - $jid = $peer_name.'@'.$peer_server; - if (!$nickname) { - - $nickname = $not_in_r[$lang]; - $jid = $peer_server; - - } - $html->set_body(' - - - - - - - '); - } - - $html->set_body(' -
    '.$my_links_link[$lang].''.$my_links_chat[$lang].''.$my_links_desc[$lang].'
    '.verbose_date($entry['datat'],$months_names).' '.cut_nick(htmlspecialchars($nickname)).' ('.htmlspecialchars($jid).')  '.$desc.' '.$del_my_link[$lang].' 
    - '); - -} -require_once("footer.php"); - -?> diff --git a/jorge/not_enabled.php b/jorge/not_enabled.php deleted file mode 100644 index 7a86b55..0000000 --- a/jorge/not_enabled.php +++ /dev/null @@ -1,105 +0,0 @@ -get('log_status')!== null) { - - header("Location: index.php"); - -} - -$action = $_POST[activate]; -$user_name = $sess->get('uid_l'); - -if ($action === $activate_m[$lang]) { - - - if ($db->get_user_id($user_name) === true) { - - if (!$db->result->user_id) { - - $db->insert_user_id($user_name); - - } - - if ($db->insert_new_settings($user_name) === true) { - - $html->set_body('
    '.$act_su[$lang].'
    '.$act_su2[$lang].'
    -
    - '); - - if ($db->get_user_id($user_name) === true) { - - $user_id = $db->result->user_id; - $db->set_user_id($user_id); - // non critical error - if ($db->set_jorge_pref("1","2") === false OR $db->set_jorge_pref("2","1") === false) { - - $html->alert_message('Ooops something goes wrong...its still beta...please contact system admin with this message'); - - } - - $sess->set('log_status',true); - $sess->set('view_type','2'); - $db->set_logger("7","1",$rem_adre); - - } - else { - - $html->alert_message('Ooops something goes wrong...its still beta...'); - - } - - } - else { - - $html->alert_message('Ooops something goes wrong...its still beta...'); - } - - } - else { - - $html->alert_message('Ooops something goes wrong...its still beta...'); - } - } - else { - - $user_name=htmlspecialchars($user_name); - $html->set_body($act_info[$lang].''.$user_name.' ('.$user_name.'@'.XMPP_HOST.')


    -
    -
    - -
    -

    '.$warning1[$lang].'
    '.$devel_info[$lang].'


    -
    -
    - - -
    -
    - '); -} - -require_once("footer.php"); -?> - diff --git a/jorge/search_v2.php b/jorge/search_v2.php deleted file mode 100644 index 18ddf13..0000000 --- a/jorge/search_v2.php +++ /dev/null @@ -1,593 +0,0 @@ -decrypt_url($predefined) === true) { - - $search_phase = "from:".$enc->jid; - - } - else { - - unset($search_phase); - unset($predefined); - } - -} - -if ($next_link) { - - if($enc->decrypt_url($next_link) === true) { - - $tslice_next = $enc->tslice; - $search_phase = $enc->search_phase; - $offset_arch = $enc->offset_arch; - $offset_day = $enc->offset_day; - $tag_count = $enc->tag_count; - - } - else { - - unset ($next_link); - unset ($search_phase); - } - -} - -if ($tag_count=="t") { - - $start_from = $offset_day; - - } - else{ - - $start_from = null; - } - -$plain_phase = $search_phase; // fix me - -require_once("upper.php"); - -//need to initialize counter here -$r=0; - -// Check if user have set up OwnName -$db->get_own_name(); -if ($db->result->own_name) { - - $own_name = $db->result->own_name; - - } - else{ - - $own_name = false; - -} - -// we need to rewrite this part internaly... -if ($search_phase!="") { - - // check if we are using parametrized search or not - $qquery = is_query_from($search_phase); - - // parametric search - if ($qquery[from] == "t") { - - $user_chat_search = "1"; // temp hack - unset($search_phase); - list($user_name, $server) = split("@", $qquery[talker]); - $db->get_user_id($user_name); - $user_name = $db->result->user_id; - $db->get_server_id($server); - $server = $db->result->server_id; - $search_phase=$qquery[query]; - - } - - - if ($search_phase) { - - if ($db->create_search_results_table() === false) { - - $html->alert_message($oper_fail[$lang]); - } - - else { - - $score="score"; - } - } - - - //main table - if ($time2_start AND $time2_end) { - - $html->status_message($search_warn[$lang].': '.$time2_start.' - '.$time2_end); - - } - else { - - $time2_start = null; - $time2_end = null; - } - - $html->set_overview('

    '.$search_res[$lang].'

    - - ' - ); - - if ($offset_arch) { - - $type_p="6"; - - } - else { - - $type_p="1"; - - } - - // run optimized query in specyfic conditions - if ($qquery[words]=="t" AND $qquery[from]=="t") { - - $type_p="8"; - - } - - if ($type_p==="1" OR $type_p==="8") { - - $db->get_uniq_chat_dates($time2_start, $time2_end, false, $offset_arch, $user_name,$server); - - } - elseif($type_p==="6") { - - $db->get_uniq_chat_dates($time2_start, $time2_end, true, $offset_arch, $user_name,$server); - - } - - debug(DEBUG,"Selected search type: $type_p (first stage)"); - - $result = $db->result; - - // query offsets init for calculations: - $arch_table = count($result); - $external=0; - $internal = $offset_day; - - // set string for searching - if ($search_phase) { - - $db->set_user_query($search_phase); - - } - - foreach($result as $entry) { - - $external++; - $time_slice = $entry["at"]; - - // sub query - - if ($search_phase) { - - $type="4"; - - } - - if ($user_chat_search) { - - if ($qquery['words']=="t") { - - $type="5"; - - } - - elseif($qquery['words'] == "f") { - - $type="7"; - } - - } - - $a++; - - if ($type==="4") { - - $db->search_query($time_slice); - - } - elseif($type==="5") { - - $db->search_query_in_user_chat($user_name,$server,$time_slice,$start_from); - - } - elseif($type==="7") { - - $db-> search_query_chat_stream($user_name,$server,$time_slice,$start_from); - - } - - debug(DEBUG,"Selected search type: $type (second stage)"); - - $search_result = $db->result; - $num_rows = count($search_result); - - $day_mark=0; - if ($num_rows!="0") { - - foreach ($search_result as $results) { - - // if there is no "from:" clausule perform normal search - if ($type!="7") { - - $body = base64_encode($results[body]); - - if ($db->insert_data_to_result_table ( - $results[ts], - $time_slice, - $results[peer_name_id], - $results[peer_server_id], - $results[direction], - $body, - $results[score], - $results[ext] - ) === false ) { - - - $html->alert_message($oper_fail[$lang]); - - } - - } - - else { - - $internal++; - $day_mark++; - - // we like colors dont we? - if ($results["direction"] == "to") { - - $col="e0e9f7"; - } - - else { - - $col="e8eef7"; - - } - - $to_user = $results["peer_name_id"]; - $to_server=$results["peer_server_id"]; - - // let's make a link - $to_base = $enc->crypt_url("tslice=$time_slice&peer_name_id=$to_user&peer_server_id=$to_server"); - - // time calc - $pass_to_next = $results["ts"]; - $new_d = $results["ts"]; - $time_diff = abs((strtotime("$old_d") - strtotime(date("$new_d")))); - $old_d = $pass_to_next; - - // split line - if ($time_diff>$split_line AND $day_mark>1 AND $type!="4") { - - $in_minutes = round(($time_diff/60),0); - $html->set_body(' - '); - } - - // talker and server names - $db->get_user_name($results[peer_name_id]); - $talk = $db->result->username; - $db->get_server_name($results[peer_server_id]); - $sname = $db->result->server_name; - // cleaning username - $jid = htmlspecialchars($talk); - - $html->set_body(' - - '); - - // username from user roster - $talk = query_nick_name($ejabberd_roster,$talk,$sname); - - // if there is no user in roster - advise that - if ($talk=="f") { - - $talk=$not_in_r[$lang]; - - } - - // threaded view - if ($results["direction"] == "from") { - - $out=$talk; - $tt=$tt+1; - $aa=0; - } - else { - $out = TOKEN; - $aa=$aa+1; - $tt=0; - - } - - if ($aa<2 AND $tt<2) { - - $html->set_body(''); - - } - else { - - $html->set_body(''); - - } - - // end threaded view - - // message body - $body_message=wordwrap(str_replace("\n","
    ",htmlspecialchars($results["body"])),107,"
    ",true); - $html->set_body(''); - - // run pagination code only if search contains from: clausule - /* - The pagination code havent been changed after upgrade to search_engine_v2 - it work well so if one want to improve it - f.e. by adding "back" button be my guest...current code is nightmare :/ - */ - $r=$r+1; - debug(DEBUG,"all: $r, num_r: $num_rows, internal: $internal"); - if ($r==$num_search_results) { - - if ($num_rows>$internal) { - - debug(DEBUG,"-->more results in this day...$entry[at] offset: $internal"); - $tag_count="t"; - } - - $next_r=$external+$offset_arch; - debug(DEBUG,"before cutdown: $next_r"); - // back to one day and continue with offset - if ($tag_count=="t") { - - $next_r=$next_r-1; - - } - - debug(DEBUG,"after cutdown: $next_r"); - debug(DEBUG,"Internal: $internal, offset: $offset_day, is_tag: $s_variables[tag_count]"); - // if the same day - we increase offset - if ($internal==$offset_day AND $s_variables[tag_count] == "t") { - - $internal=$internal+$offset_day; - debug(DEBUG,"Increasing offset..."); - - } - - // hack - if ($qquery[from] == "t") { - - $plain_phase=str_replace("@","//",$plain_phase); - - } - - $trange = $enc->crypt_url("time_start=$time2_start&time_end=$time2_end"); - $lnk_n = $enc->crypt_url("tslice=$entry[at]&offset_arch=$next_r&offset_day=$internal&search_phase=$plain_phase&tag_count=$tag_count"); - - $html->set_body(' - - - - '); - break 2; - - } - - - - } - - - } - - } - - else{ - - // if we haven't found anything increase counter by one... - $b++; - } - - $start_from = null; // reset... - $internal=0; - $day_mark=1; - if ($num_rows!=0 AND $type=="7") { - - if ($arch_table == $external) { - - $html->set_body(''); - } - - elseif($type=="7") { - - $html->set_body(''); - - // initialize thread - $aa="0"; - $tt="0"; - } - } - - // end of main loop - } - - // if normal search: - if ($type!="7" AND $type!==NULL) { - - $db->get_search_results(); - $result = $db->result; - $num_results = count($result); - $html->set_body(' - '); - - foreach ($result as $dat) { - - //building link: - $to_base = $enc->crypt_url("tslice=$dat[time_slice]&peer_name_id=$dat[peer_name_id]&peer_server_id=$dat[peer_server_id]"); - - // get the name of user that we was talking to - $db->get_user_name($dat[peer_name_id]); - $talk = $db->result->username; - - // get it's server name - $db->get_server_name($dat[peer_server_id]); - $sname = $db->result->server_name; - - // cleanup jid - $jid = htmlspecialchars($talk); - - // color every second line... - if ($col=="e0e9f7") { - - $col="e8eef7"; - - } - else { - - $col="e0e9f7"; - - } - - // get username from user roster: - $talk = query_nick_name($ejabberd_roster,$talk,$sname); - - // if user is not in list, advise about that - if ($talk === "" ) { - - $talk=$not_in_r[$lang]; - - } - - // now we want to know who was talking to who... - if ($dat["direction"] == "to") { - - $fr=$to_u[$lang]; - - } - else { - - $fr=$from_u[$lang]; - - } - - // ... and what was talking, and format that ... - $body_talk = wordwrap(str_replace("\n","
    ",htmlspecialchars(base64_decode($dat["body"]))),107,"
    ",true); - - // advise user if chat is deleted. Extension=1 stands for "Chat temporary deleted" or "Chat awaiting deletion" - if ($dat[ext] == 1) { - - $html->set_body(''); - - } - - // opening line - if ($dat[ext]!=1) { - - $html->set_body(''); - - } - else { - - $html->set_body(''); - - } - - // content - $html->set_body(' - - - - ' - ); - - } - - $html->set_body(''); - - } - - if($a==$b) { - - $html->set_body(''); - - } - - $html->set_body('
    '.$time_t[$lang].''.$talks[$lang].''.$thread[$lang].''.$score.'
    '.verbose_split_line($in_minutes,$verb_h[$lang],$in_min[$lang]).'
    '.$results["ts"].' '); - - if ($out === TOKEN) { - - if ($own_name !== false) { - - $html->set_body(cut_nick(htmlspecialchars($own_name))); - - } - else{ - - $html->set_body(cut_nick(htmlspecialchars($out))); - - } - } - else { - - $html->set_body(cut_nick(htmlspecialchars($out))); - - } - - $html->set_body('   -'.$body_message.'
    - - '.$search_next[$lang].'
    '.$no_more[$lang].'
    '.$nx_dy[$lang].'
    '.$search_tip[$lang].' '.$num_results.''.$search_why[$lang].'
    '.$marked_as_d[$lang].'
    '.$dat["ts"].''.$fr.'  '.cut_nick($talk).'  '.$body_talk.''.round($dat[score],2).'
    '.$no_result[$lang].'
    '); - - } - - else { - - // if user input is empty: - $html->set_body('

    '.$search1[$lang].'




    '); - -} - -require_once("footer.php"); -?> diff --git a/jorge/settings.php b/jorge/settings.php deleted file mode 100644 index 8b92482..0000000 --- a/jorge/settings.php +++ /dev/null @@ -1,330 +0,0 @@ -get('validate_number') !== $_POST['validate_form']) { - - debug(DEBUG," - Invalid control number, destroying POST data. Control should be: ".$sess->get('validate_number')); - unset($_POST); - $html->alert_message($oper_fail[$lang]); - - } - else{ - - debug(DEBUG," - POST data seems to be ok."); - - } - -} - -// Generate new control data for forms -$set_control = md5(rand(10000,10000000)); -$sess->set("validate_number",$set_control); -debug(DEBUG,"Setting new control data: $set_control"); - -// toggle message saving -if ($tgle) { - - debug(DEBUG,"Trying to change archiving option"); - if ($tgle === $arch_on[$lang]) { - - if($db->set_log(true) === true) { - - $sess->set('log_status',true); - $db->set_logger("7","1"); - $html->status_message($status_msg2[$lang]); - - } - else{ - - $html->alert_message($oper_fail[$lang]); - - } - - } - elseif($tgle === $arch_off[$lang]) { - - if($db->set_log(false) === true) { - - $sess->set('log_status',false); - $db->set_logger("6","1"); - $html->status_message($status_msg3[$lang]); - $html->system_message($status_msg1[$lang]); - - } - else{ - - $html->alert_message($oper_fail[$lang]); - - } - - } -} - -// Control diplaying of special contacs -if ($vspec) { - - if ($db->set_jorge_pref("3",$vspec) === true) { - - $html->status_message($con_saved[$lang]); - - } - else{ - - $html->alert_message($oper_fail[$lang]); - - } - -} - -// delete entire archive -if ($_POST['erase_confirm'] === "true") { - - if ($_POST['del_all'] === $settings_del[$lang]) { - - debug(DEBUG," - Trying to erase all message archives"); - if ($db->erase_all() === true) { - - $html->status_message($deleted_all[$lang]); - $db->set_logger("9","2"); - debug(DEBUG," - DONE"); - - } - else{ - - $html->alert_message($delete_error[$lang]); - debug(DEBUG," - FAILED"); - - } - - } - -} - -// set own name -if ($_POST['own_name_value']) { - - // Validation is done by class, so we pass values there... - if ($db->set_own_name($_POST['own_name_value']) === true) { - - $html->status_message($con_saved[$lang]); - - }else{ - - $html->alert_message($oper_fail[$lang]); - - } - -} - -$html->set_overview('

    '.$settings_desc[$lang].'

    '.$settings_desc_detail[$lang].''); -$html->set_body('
    - '); - -$html->set_body(' - - - - - '); - -if ($db->get_jorge_pref("3") === false) { - - $html->alert_message($oper_fail[$lang]); - -} - -$special_select = $db->result->pref_value; - -if ($special_select === "2") { - - $n_is_sel = "selected"; - - } - else{ - - $y_is_sel = "selected"; - -} - -$html->set_body(' - - - - - -'); - -$html->set_body(' - - - -'); - -$html->set_body(' - - -'); - -$html->set_body(' - - - '); - -$html->set_body('
    '.$setting_d1[$lang].'
    '.$setting_d2[$lang].' - - - -
    '.$spec_contact_enable[$lang].'(?) -
    '.$select_view[$lang].' - - -
    '.$sel_language[$lang].' - - -
    '.$own_name_enter[$lang].'(?) - - -


    '.$stats_personal_d[$lang].''); - -$db->get_personal_sum(); -$total_messages = number_format($db->result->cnt); - -$html->set_body('

    '.$stats_personal[$lang].' '.$total_messages.'

    '.$stats_personal_top[$lang].'

    '); - -$db->get_personal_top(); -$results = $db->result; - -if (count($results)!=0) { - - $html->set_body(' - - - '); - - foreach ($results as $result) { - - $db->get_user_name($result[peer_name_id]); - $user_name = $db->result->username; - $db->get_server_name($result[peer_server_id]); - $server_name = $db->result->server_name; - $nickname=query_nick_name($ejabberd_roster,$user_name,$server_name); - $to_base = $enc->crypt_url("tslice=$result[at]&peer_name_id=$result[peer_name_id]&peer_server_id=$result[peer_server_id]"); - $html->set_body(' - - '); - - } - - $html->set_body('
    '.$stats_personal_count[$lang].''.$stats_peer[$lang].''.$stats_when[$lang].'
    '.$result[count].''.$nickname.'  - ('.htmlspecialchars($user_name).'@'.htmlspecialchars($server_name).') - '.$result[at].'
    '); - - } - else { - - $html->set_body('
    '.$no_archives[$lang].'
    '); - -} - -$html->set_body('
    '); -require_once("footer.php"); -?> diff --git a/jorge/simpletree.css b/jorge/simpletree.css deleted file mode 100644 index 2c14ea6..0000000 --- a/jorge/simpletree.css +++ /dev/null @@ -1,28 +0,0 @@ -.treeview ul{ /*CSS for Simple Tree Menu*/ -margin: 0; -padding: 0; -} - -.treeview li{ /*Style for LI elements in general (excludes an LI that contains sub lists)*/ -background: url(img/list.png) no-repeat left center; -background-color: transparent; -list-style-type: none; -padding-left: 22px; -margin-bottom: 3px; -} - -.treeview li.submenu{ /* Style for LI that contains sub lists (other ULs). */ -background: url(img/closed.png) no-repeat left 1px; -background-color: transparent; -cursor: hand !important; -cursor: pointer !important; -} - - -.treeview li.submenu ul{ /*Style for ULs that are children of LIs (submenu) */ -display: none; /*Hide them by default. Don't delete. */ -} - -.treeview .submenu ul li{ /*Style for LIs of ULs that are children of LIs (submenu) */ -cursor: default; -} diff --git a/jorge/stats.php b/jorge/stats.php deleted file mode 100644 index 70c0688..0000000 --- a/jorge/stats.php +++ /dev/null @@ -1,285 +0,0 @@ -set_body('
    '.$stats_vhost_select[$lang].'
    '); - -if ($vhost_valid === true) { - - - $db->total_messages($vhost_active); - $total_messages = $db->result; - $html->set_body('

    '.$stats_for[$lang].$vhost_active.'

    - '.$stats_messages[$lang].' '.number_format($total_messages[1][total_messages]).' - '.$stats_messages_b[$lang].''.number_format($total_messages[1][total_chats]).''.$stats_messages_c[$lang].'

    -
    '); - - // get dates - $today = date("Y-n-j"); - $yesterday = date("Y-n-j", strtotime("-1 day")); - $last_week = date("Y-n-j", strtotime("-7 days")); - for ($ds=0;$ds<=4;$ds++) { - - $days[$ds] = date("Y-n-j", strtotime("-$ds day")); - - } - - // Top 10 - $html->set_body(' -
    '.$stats_top[$lang].'
    '); - foreach ($days as $current_day) { - - $i=0; - $html->set_body(''.verbose_date($current_day,$months_names,$weekdays,true).' :
    '); - $db->get_top_ten($current_day,$vhost_active); - $result = $db->result; - foreach ($result as $entry) { - - $i++; - $db->get_user_name($entry[owner_id],$vhost_active); - $local_user = $db->result->username; - $db->get_user_name($entry[peer_name_id],$vhost_active); - $peer_name = $db->result->username; - $db->get_server_name($entry[peer_server_id],$vhost_active); - $peer_server = $db->result->server_name; - $html->set_body(' -  '.$i.'. '.htmlspecialchars($local_user).'@'.$vhost_active.' --> - '.htmlspecialchars($peer_name).'@'.htmlspecialchars($peer_server).' ('.$entry[count].')
    - '); - - } - $html->set_body('
    '); - - } - $html->set_body('
    '); - - // get data for graphs. We can now draw data only if we have full array. This is known issue. - $db->get_monthly_stats($vhost_active); - $result = $db->result; - - if (count($result)<30) { - - $html->status_message($stats_not_eno[$lang]); - - } - else { - - - foreach ($result as $entry) { - - $i++; - $f[$i] = $entry[time_unix]; - $d[$i] = $entry[messages]; - $e[$i] = $entry[users_total]; - - } - - // hourly stats - $db->get_hourly_stats($yesterday,$vhost_active); - $result = $db->result; - foreach ($result as $entry) { - - $hs[$entry[hour]] = $entry[value]; - } - - // weekly stats - $db->get_weekly_stats($last_week,$yesterday,$vhost_active); - $result = $db->result; - foreach ($result as $entry) { - - $idx++; - $hy[$idx] = $entry[value]; - - } - - $html->set_body(' - - -
    -

    -

    -

    -
    -
    - - - '); - - } - -} - -require_once("footer.php"); -?> diff --git a/jorge/style.css b/jorge/style.css deleted file mode 100644 index 335a36a..0000000 --- a/jorge/style.css +++ /dev/null @@ -1,403 +0,0 @@ -body { - background-color: #ffffff; - font-family: Arial; - font-size: 9pt; - -} - -h2 { - font-family: Arial; - font-size: 10pt; - } - -input.cc { width: 400px; } -input:focus.cc2 { width: 400px; border: 2px solid #73a6ff; } -select.cc { width: 70pt; border: 1px solid gray; } -select.cc2 { width: 40pt; border: 1px solid gray; text-align: center; } -select.cc3 { text-align: center; } -select.settings { - text-align: center; - font-size: x-small; - width: 100pt; -} -input.settings { - text-align: center; - font-size: x-small; - width: 100pt; -} - -input.log { width: 250px; border: 1px solid gray;} -input:focus.log { width: 250px; border: 1px solid #73a6ff;} -input.ccc { width: 400px; border: 1px solid gray; } -textarea.ccc { width: 400px; border: 1px solid gray; } - -div.contain { - #border: 1px dashed #333; -} - -div.spacer_div { - clear: both; -} - -tr.header { - background-image: url(img/bar_new.png); - background-repeat:repeat-x; - color: #fff; - font-weight: bold; -} - -tr.foot { - background-image: url(img/bar_new.png); - background-repeat:repeat-x; - color: #fff; -} - -td.rowspace { - - padding-left: 5px; - padding-right: 5px; - - -} - -input.red { - background-color: #e0e9f7; - font-size: 12px; - color: #000000; - border:1px solid; - border-color: #ffffff; - } - -input.fav { - background-color: transparent; - font-size: 8pt; - font-weight: bold; - color: #ffffff; - border:0px solid; - border-color: #ffffff; - vertical-align: bottom; -} - -input.fav_main { - background-color: transparent; - font-size: 8pt; - font-weight: bold; - color: #65a5e4; - border:0px solid; - border-color: #ffffff; - vertical-align: bottom; -} - - -input.submit { - - background-color: transparent; - font-size: 8pt; - font-weight: bold; - color: #ffffff; - border:0px solid; - border-color: #ffffff; - vertical-align: bottom; - text-decoration: underline; -} - -div.message { - background-color: #fad163; - font-weight: bold; - text-align: center; - font-size: x-small; - width: 550px; -} - -div.system { - background-color: #ffffff; - font-weight: bold; - text-align: center; - font-size: x-small; - width: 350px; - border-width: 1px; - border-color: #0000ff; - border-style: solid; -} - -p.message { - background-color: #fad163; - font-weight: bold; - text-align: center; - font-size: x-small; - width: 400px; -} - - - - -td.message { - background-color: #fad163; - color: #fff; - font-size: x-small; - text-align: center; -} - -table.ff { - font-size: 9pt; - font-family: Arial; - } - -span.hlt { - background-color: yellow; - } - -td.time_chat { - background-color: #669dd6; - color: #fff; - text-align: center; - } - -tr.main_s { - color: black; - font-weight: bold; - font-size: 12px; - text-decoration: underline; - } - -tr.maint { - font-weight: bold; - background-color: #c3d9ff; - color: #000000; - } - - -tr.main_row_a { background-color: #e8eef7; } -tr.main_row_b { background-color: #e0e9f7; } -tr.main_row_error { background-color: #de5b5b; } -tr.main_row_headline { background-color: #9fd8ee; } -tr.main_row_message { background-color: #ade8df; } -tr.main_row_group_to { background-color: #fdffbb; } -tr.main_row_group_from { background-color: #fdffd4; } -tr.spacer { background-color: #afccf7; } -tr.spacerb { background-color: #ffffcc; } -td.main_row_special { font-size: x-small; font-style: italic; } - -tr.splitl { - - background-color: #f1f7ff; - font-size: 10px; - color: grey; - text-align: center; - -} - - - -a.menue { - color: #0707cd; -} - -a { - color: #000000; - text-decoration: none; -} - -a.mmenu { - color: white; - text-decoration: none; -} - -a:hover.mmenu { - color: white; -} - -a.foot { - color: #65a5e4; - text-decoration: none; -} - -a.nav_np { - - color: #fff; - text-decoration: none; - font-weight: bold; - -} - -a:hover.nav_np { - - color: #FFCC00; - font-weight: bold; - -} - -a.menu_chat { - color: #fff; - text-decoration: none; - -} - -a:hover { - - color: #136ef7; - text-decoration: none; - -} - -td.cnter { - - font-size: 7pt; - -} -a.delq { - color: red; -} - -a.export { - - color: #4145ff; - -} - -a.clickl { - color: #4145ff; - text-decoration: underline; - } - - -input.btn{ - color:#000000; - font-family:'trebuchet ms',helvetica,sans-serif; - font-size:84%; - font-weight:bold; - background-color:#e8eef7 ; - border:1px solid; - border-top-color:#696; - border-left-color:#696; - border-right-color:#363; - border-bottom-color:#363; -} - - -input.btn_set{ - color:#fff; - font-size: x-small; - background-color:#6daae7; - border:0px solid; - border-top-color:#696; - border-left-color:#696; - border-right-color:#363; - border-bottom-color:#363; -} - -input.c_map_class{ - color: grey; - font-size: x-small; - text-align: center; - background-color:#fff; - border:1px solid; -} - -input:focus.c_map_class { - color: grey; - font-size: x-small; - text-align: center; - background-color:#fff; - border:1px solid #73a6ff; - -} - -#tooltip.fancy { - background-color: #ffffcc; - border: 1px solid #afccf7; - color: #333333; - padding: 4px; - -moz-border-radius-bottomleft: 7px; - -moz-border-radius-bottomright: 7px; - -moz-border-radius-topleft: 0; - -moz-border-radius-topright: 7px; - opacity: .85; - max-width: 60em; - -} - - -.calbck { - background-image: url(img/cal_bck.png); - background-repeat: repeat-x; - background-color: transparent; -} - -.calbck_con { - background-image: url(img/cal_bck2.png); - background-repeat: repeat-x; - background-color: transparent; -} - -.calhead { - font-family: Tahoma; - font-size: 10px; - font-weight: bold; - color: #FFFFFF; -} -.calweek { - font-family: Tahoma; - font-size: 10px; - color: #FFFFFF; -} -.caldays { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #FFFFFF; -} -.caldaysnow { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #FFFFFF; -} -.caldaysfeat { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #b9b9c1; -} -.caldayssel { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #FFFFFF; - background-color: #346DA5; -} -.caldays2 { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #FFCC00; -} -a.caldays2 { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #FFCC00; -} - -a.caldays3 { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #ffffff; -} - -a.caldays4 { - font-family: Arial, Helvetica, sans-serif; - font-size: 10px; - color: #bebebe; -} - -a:hover.caldays3 { - - color:#FFCC00; - -} - -.calbckleft { - background-image: url(img/cal_bck_left2.png); - background-repeat: repeat-y; - background-color: transparent; -} -.calbckright { - background-image: url(img/cal_bck_right2.png); - background-repeat: repeat-y; - background-color: transparent; -} diff --git a/jorge/tools/gen_stats.php b/jorge/tools/gen_stats.php deleted file mode 100644 index d5ba51e..0000000 --- a/jorge/tools/gen_stats.php +++ /dev/null @@ -1,55 +0,0 @@ - jabber_org -$vhost="_VHOST_FOR_WHICH_STATS_ARE_MADE"; # dotted form ex: jabber.org - -$day_stats_a = date("Y-n-j", strtotime ("-1 day")); // if you mist stats for some day change to: date("Y-n-d", strtotime ("-1 day", strtotime("_YOUR_MISSING_DAY_"))); and generate stats manualy. -$day_stats_b = $day_stats_a; - -for ($ds=0;$ds<24;$ds++) { - - $de=$ds+1; - if ($de==24) {$de=0; $day_stats_b = date("Y-n-d", strtotime ("+1 day",strtotime($day_stats_a))); } - $hourly_t="select count(owner_id) from `logdb_messages_$day_stats_a"."_"."$xmpp_host` where timestamp > unix_timestamp('$day_stats_a $ds:00:00') and timestamp < unix_timestamp('$day_stats_b $de:00:00')"; - $result=mysql_query($hourly_t); - $row=mysql_fetch_row($result); - $stats_insert="insert into jorge_stats (day,hour,value,vhost) values('$day_stats_a','$ds','$row[0]','$vhost')"; - mysql_query($stats_insert) or die("SQL Error\n"); - -} - -print "done\n"; - - - -?> diff --git a/jorge/tools/optimize_tables.php b/jorge/tools/optimize_tables.php deleted file mode 100644 index 6a61849..0000000 --- a/jorge/tools/optimize_tables.php +++ /dev/null @@ -1,63 +0,0 @@ - diff --git a/jorge/tools/trash_cleanup.php b/jorge/tools/trash_cleanup.php deleted file mode 100644 index ea5148a..0000000 --- a/jorge/tools/trash_cleanup.php +++ /dev/null @@ -1,116 +0,0 @@ - [jorge] Cleaning up trash......."; -$conn=mysql_connect("_MYSQL_HOST_", "_USER_", "_PASSWORD_") or die ("DB connect failed\n"); -mysql_select_db ("_DB_NAME_") or die ("DB select failed\n"); -$xmpp_host="_YOUR_XMPP_HOST_"; - -$query="select owner_id, peer_name_id,peer_server_id,idx,date as tslice,vhost from pending_del where timeframe < date_format((date_sub(curdate(),interval 1 month)), '%Y-%c-%e')"; -$result=mysql_query($query); - -if (mysql_num_rows($result)>0) { - - $i=0; - - while($row=mysql_fetch_array($result)) { - - $i++; - $ch_del="delete from - `logdb_messages_$row[tslice]"."_$xmpp_host` - where - owner_id='$row[owner_id]' - and - peer_name_id='$row[peer_name_id]' - and - peer_server_id='$row[peer_server_id]' - and - ext = '$row[idx]' - "; - $li_del="delete from - jorge_mylinks - where - owner_id='$row[owner_id]' - and - ext='$row[idx]' - and - peer_name_id = '$row[peer_name_id]' - and - peer_server_id='$row[peer_server_id]' - and - datat = '$row[tslice]' - and - vhost = '$row[vhost]' - "; - $fa_del="delete from - jorge_favorites - where - owner_id='$row[owner_id]' - and - ext='$row[idx]' - and - peer_name_id = '$row[peer_name_id]' - and - peer_server_id='$row[peer_server_id]' - and - vhost = '$row[vhost]' - "; - $pe_del="delete from pending_del - where owner_id='$row[owner_id]' - and - peer_name_id = '$row[peer_name_id]' - and - peer_server_id='$row[peer_server_id]' - and - date='$row[tslice]' - and - idx='$row[idx]' - and - vhost = '$row[vhost]' - "; - mysql_query("$ch_del") or die("Error #1\n"); - mysql_query("$li_del") or die("Error #2\n"); - mysql_query("$fa_del") or dir("Error #3\n"); - mysql_query("$pe_del") or die("Error #4\n"); - - } - - print "Deleted $i chats.\n"; - - } - - else - - { - - print "Nothing to delete.\n"; - - } - -?> diff --git a/jorge/trash.php b/jorge/trash.php deleted file mode 100644 index b67bc1d..0000000 --- a/jorge/trash.php +++ /dev/null @@ -1,167 +0,0 @@ -set_overview('

    '.$trash_name[$lang].'

    '.$trash_desc[$lang].''); - -if ($enc->decrypt_url($_GET[a]) === true) { - - $tslice = $enc->tslice; - $talker = $enc->peer_name_id; - $server = $enc->peer_server_id; - $action = $enc->action; - $lnk = $enc->lnk; - - } - else { - - $action = null; - -} - -if ($_GET['idx']) { - - $idx = $_GET['idx']; - - if ($enc->decrypt_url($idx) === true) { - - if($db->set_ext_index($enc->single) !== true) { - - unset($idx); - unset($action); - - } - - $idx = $enc->single; - - } - else{ - - unset($idx); - unset($action); - - } - -} - -if ($action=="undelete") { - - if ($db->move_chat_from_trash($talker,$server,$tslice,$lnk,$idx) === true) { - - $back_link = $enc->crypt_url("tslice=$tslice&peer_name_id=$talker&peer_server_id=$server"); - $html->status_message($undo_info[$lang].'
    '.$trash_vit[$lang].''); - - // number of items in trash - $db->get_trash_count(); - $tr_n = $db->result->cnt; - - } - - else - - { - - unset($talker); - $html->alert_message($oper_fail[$lang]); - - } - -} - -if ($action==="delete") { - - if ($db->remove_messages_from_trash($talker,$server,$tslice) === true) { - - $html->status_message($del_info[$lang]); - // number of items in trash - $db->get_trash_count(); - $tr_n = $db->result->cnt; - - } - else { - - $html->alert_message($oper_fail[$lang]); - - } - - -} - -if ($tr_n < 1) { - - $html->set_body('

    '.$trash_empty[$lang].'

    ' ); - } - - else - - { - $html->set_body(' -
    - - - - '); - $db->get_trashed_items(); - $result = $db->result; - foreach ($result as $entry) { - - $db->get_user_name($entry[peer_name_id]); - $talker = $db->result->username; - $db->get_server_name($entry[peer_server_id]); - $server_name = $db->result->server_name; - $tslice = $entry["date"]; - $nickname = query_nick_name($ejabberd_roster,$talker,$server_name); - if (!$nickname) { - - $nickname = $not_in_r[$lang]; - unset($malpa); - - } - else { - - $malpa = "@"; - - } - $reconstruct_link = $enc->crypt_url("tslice=$tslice&peer_name_id=$entry[peer_name_id]&peer_server_id=$entry[peer_server_id]"); - $undelete_link = $enc->crypt_url("tslice=$tslice&peer_name_id=$entry[peer_name_id]&peer_server_id=$entry[peer_server_id]&lnk=$reconstruct_link&action=undelete"); - $delete_link = $enc->crypt_url("tslice=$tslice&peer_name_id=$entry[peer_name_id]&peer_server_id=$entry[peer_server_id]&lnk=$reconstruct_link&action=delete"); - $idx = $enc->crypt_url("single=".$entry[idx].""); - - $html->set_body(' - - - - - - - '); - - } - - $html->set_body(' -
    '.$my_links_chat[$lang].''.$logger_from_day[$lang].''.$del_time[$lang].'
    '.$nickname.' ('.htmlspecialchars($talker).$malpa.htmlspecialchars($server_name).')'.$tslice.''.$entry[timeframe].''.$trash_undel[$lang].''.$trash_del[$lang].'
    - '); - } - -require_once("footer.php"); -?> diff --git a/jorge/upper.php b/jorge/upper.php deleted file mode 100644 index f785cd7..0000000 --- a/jorge/upper.php +++ /dev/null @@ -1,490 +0,0 @@ -get('log_status') === null) { - - header ("Location: not_enabled.php"); - exit; - -} - -// number of my links saved... -$db->get_mylinks_count(); -$my_links_count = $db->result->cnt; - -// number of items in trash -$db->get_trash_count(); -$tr_n = $db->result->cnt; - -// number of favorites -$db->get_favorites_count(); -$favorites_count = $db->result->cnt; - -// get preferences for saving -$pref_id=$_GET['set_pref']; -$pref_value=$_GET['v']; - -// save preferences ONLY. Setting language in session is done in headers, here we only save that preferences. -if ($_GET['set_pref']) { - - // Language selection - if ($pref_id === "2") { - - //Rewrite array for late reuse - $language_change = $language_support; - // Here the $pref_value is actually $lng_sw - $pref_value = $_GET['lng_sw']; - while(array_keys($language_change)) { - - $lang_key = key($language_change); - if (in_array($pref_value,$language_change[$lang_key])) { - - debug(DEBUG,"Saving language preferences into database..."); - if ($db->set_jorge_pref($pref_id,$pref_value) === false) { - - $html->alert_message($oper_fail[$lang],"message"); - debug(DEBUG,"Preferences not saved due to error"); - - } - else{ - - $html->status_message($con_saved[$lang]); - debug(DEBUG,"Preferences saved successfuly"); - - } - - break 1; - - } - - array_shift($language_change); - - } - } - - // default view type - if ($pref_id ==="1") { - - debug(DEBUG,"Saving view selection into database"); - if($pref_value === "1" OR $pref_value === "2") { - - if ($db->set_jorge_pref($pref_id,$pref_value) === false) { - - $html->alert_message($oper_fail[$lang],"message"); - debug(DEBUG,"Preferences not saved due to error"); - - } - else{ - - // Display status message only if setting via control panel - if ($_GET['ref'] === "settings") { - - $html->status_message($con_saved[$lang]); - debug(DEBUG,"Preferences saved successfuly"); - - } - - } - - $sess->set('view_type',$pref_value); - - } - } - -} - -// get preferences, if not set, fallback to standard view. -$view_type=$sess->get('view_type'); -if ($view_type=="1") { - - $view_type="main.php"; - } - elseif($view_type=="2") { - - $view_type="calendar_view.php"; - -} - -// this is menu. not nice but works ;) -if (preg_match("/search_v2.php/i",$location)) - - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - $search_loc=1; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - } - elseif(preg_match("/main.php/i",$location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - } - elseif(preg_match("/my_links.php/i",$location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.') '; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - - } - elseif(preg_match("/help.php/i",$location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - } - elseif(preg_match("/contacts.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - } - elseif(preg_match("/stats.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - - } - elseif(preg_match("/logger.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - - } - elseif(preg_match("/trash.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - - } - elseif(preg_match("/calendar_view.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - - } - elseif(preg_match("/chat_map.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - - - } - elseif(preg_match("/settings.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - } - elseif(preg_match("/favorites.php/i", $location)) - { - $menu_main=''.$menu_item_browser[$lang].''; - $menu_map=''.$menu_item_map[$lang].''; - $menu_search=''.$menu_item_search[$lang].''; - $menu_mylinks=''.$menu_item_links[$lang].' ('.$my_links_count.')'; - $menu_favorites=''.$menu_item_fav[$lang].'('.$favorites_count.')'; - $menu_contacts=''.$menu_item_contacts[$lang].''; - $menu_logger=''.$menu_item_logs[$lang].''; - $menu_trash=''.$menu_item_trash[$lang].'('.$tr_n.')'; - if (TOKEN==ADMIN_NAME) { $menu_stats=' | Stats'; } - } - -// check if archivization is currently enabled... -if ($sess->get('log_status') === false) { - - $html->system_message($status_msg1[$lang]); - -} - -if ($start) { - - $cur_loc="&start=$start"; - -} - -// Show special contact? -$db->get_jorge_pref("3"); -$show_spec = $db->result->pref_value; - -// Display special contacts? -if ($show_spec === "2") { - - $db->spec_ignore(true); - - } - else { - - $db->spec_ignore(false); - -} - -//Generate quick jump -$db->get_last_day(); -$ql_date = $db->result->at; -$quick_link = $enc->crypt_url("tslice=$ql_date"); - -$html->menu(' - - - - - - - '); - -if ($mac_user === true) { - - $html->menu(''); - -} - -$html->menu(' - - - - -
    - - '.TOKEN.'@'.XMPP_HOST.'  |   - '.$menu_item_panel[$lang].'  |   - '.$sel_client[$lang].'  |   - '.$help_but[$lang].'  |  '.$log_out_b[$lang].'
    logo
    - - '); - -if ($search_loc==1) { - - if (isset($_GET[c])) { - - $enc->decrypt_url($_GET['c']); - $time2_start = $enc->time_start; - $time2_end = $enc->time_end; - - } - - else{ - - $time2_start=$_POST[time2_start]; - $time2_end=$_POST[time2_end]; - if (validate_date($time2_start) === false) { - - unset($time2_start); - } - if (validate_date($time2_start) === false) { - - unset($time2_end); - } - - } - - if ($time2_start AND $time2_end) { - - if (strtotime("$time2_start") > strtotime("$time2_end")) { - - $alert = $time_range_w[$lang]; unset ($search_phase); - - } - } - - $db->get_uniq_chat_dates(); - $result = $db->result; - foreach ($result as $row) { - - $r++; - $to_tble[$r] = $row[at]; - - } - - $html->menu(' '); - - if ($time2_start AND !$time2_end) { - - $time2_end = $to_tble[$pass_t-1]; - - } - - if (!$time2_start AND $time2_end) { - - $time2_start = $to_tble[($t+1)-$t]; - - } - -} - -$html->menu('
    Hello Mac user!
    - '.$menu_main.' | ' - .$menu_map.' | ' - .$menu_favorites.' | ' - .$menu_mylinks.' | ' - .$menu_search.' | ' - .$menu_contacts.' | ' - .$menu_logger.$menu_stats.' | ' - .$menu_trash. - ' | '.$refresh[$lang].' -
    -

    '.$alert.'

    - '); - -// Get user roster. -$rpc_roster = $ejabberd_rpc->get_roster(); - -// creater roster object and rewrite it to portable multidimentional array -$ejabberd_roster = new roster(); - -foreach ($rpc_roster as $roster_record) { - - if ($roster_record[group]=="") { - - $roster_record[group] = $con_no_g[$lang]; - - } - - // avoid contacts without nick - if ($roster_record[nick]!="") { - - $ejabberd_roster->add_item($roster_record[jid],$roster_record[nick],$roster_record[group]); - - } -} - -?>