PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/include/database.php

http://wordcraft.googlecode.com/
PHP | 1280 lines | 698 code | 366 blank | 216 comment | 103 complexity | 7179cf9b1a411c603e83e76685a9b27e MD5 | raw file
Possible License(s): CC0-1.0, AGPL-1.0
  1. <?php
  2. /**
  3. * Lists posts made by users of the blog
  4. *
  5. * @author Brian Moon <brian@moonspot.net>
  6. * @copyright 1997-Present Brian Moon
  7. * @package Wordcraft
  8. * @license http://wordcraft.googlecode.com/files/license.txt
  9. * @link http://wordcraft.googlecode.com/
  10. *
  11. */
  12. require_once dirname(__FILE__)."/config.php";
  13. require_once dirname(__FILE__)."/WCDB.php";
  14. // Check that this file is not loaded directly.
  15. if ( basename( __FILE__ ) == basename( $_SERVER["PHP_SELF"] ) ) exit();
  16. // if init has not loaded, quit the file
  17. if(!defined("WC")) exit("common.php not loaded");
  18. /**
  19. * Generate the table names using the prefix
  20. */
  21. $WC["settings_table"] = $WC["db_prefix"]."_settings";
  22. $WC["pages_table"] = $WC["db_prefix"]."_pages";
  23. $WC["posts_table"] = $WC["db_prefix"]."_posts";
  24. $WC["users_table"] = $WC["db_prefix"]."_users";
  25. $WC["comments_table"] = $WC["db_prefix"]."_comments";
  26. $WC["tags_table"] = $WC["db_prefix"]."_tags";
  27. $WC["uri_lookup_table"] = $WC["db_prefix"]."_uri_lookup";
  28. /**
  29. * Create a new database object for these functions to use
  30. */
  31. $WCDB = new WCDB($WC["db_server"], $WC["db_name"], $WC["db_user"], $WC["db_password"]);
  32. /**
  33. * Gets the application settings.
  34. *
  35. * @return array
  36. *
  37. */
  38. function wc_db_get_settings(){
  39. global $WC, $WCDB;
  40. $sql = "select *
  41. from {$WC['settings_table']}
  42. where name in (
  43. 'akismet_key',
  44. 'allow_comments',
  45. 'base_url',
  46. 'date_format_long',
  47. 'date_format_short',
  48. 'default_description',
  49. 'default_title',
  50. 'email_comment',
  51. 'moderate_all',
  52. 'send_linkbacks',
  53. 'session_days',
  54. 'session_domain',
  55. 'session_path',
  56. 'session_secret',
  57. 'template',
  58. 'use_akismet',
  59. 'use_captcha',
  60. 'use_rewrite',
  61. 'use_spam_score',
  62. 'db_version'
  63. )";
  64. $WCDB->query($sql);
  65. $settings = array();
  66. while($rec = $WCDB->fetch()){
  67. if(!empty($rec["S"])){
  68. $settings[$rec["name"]] = json_decode($rec["data"]);
  69. } else {
  70. $settings[$rec["name"]] = $rec["data"];
  71. }
  72. }
  73. return $settings;
  74. }
  75. /**
  76. * Save the application settings.
  77. *
  78. * @param $settings Array of settings to save.
  79. * @return void
  80. *
  81. */
  82. function wc_db_save_settings($settings){
  83. global $WC, $WCDB;
  84. if(empty($settings)) return false;
  85. $success = false;
  86. $clean_arr = array();
  87. foreach($settings as $name=>$data){
  88. switch($name){
  89. case "session_days":
  90. $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>(int)$data);
  91. break;
  92. case "base_url":
  93. case "session_secret":
  94. case "session_path":
  95. case "session_domain":
  96. case "date_format_long":
  97. case "date_format_short":
  98. case "template":
  99. case "default_title":
  100. case "default_description":
  101. case "akismet_key":
  102. case "email_comment":
  103. case "db_version":
  104. $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>$WCDB->escape($data));
  105. break;
  106. case "use_rewrite":
  107. case "use_spam_score":
  108. case "use_captcha":
  109. case "use_akismet":
  110. case "moderate_all":
  111. case "allow_comments":
  112. case "send_linkbacks":
  113. $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>(bool)$data);
  114. break;
  115. default:
  116. trigger_error("Invalid field $name sent to ".__FUNCTION__.".", E_USER_WARNING);
  117. continue;
  118. }
  119. }
  120. $success = true;
  121. foreach($clean_arr as $setting){
  122. $sql = "replace into {$WC['settings_table']} set
  123. name = '$setting[name]',
  124. type = '$setting[type]',
  125. data = '$setting[data]'";
  126. if(!$WCDB->query($sql)){
  127. $success = false;
  128. }
  129. }
  130. return $success;
  131. }
  132. /**
  133. * Checks the given cookie against the database for a user
  134. *
  135. * @param $cookie The cookie value to check
  136. * @return mixed
  137. *
  138. */
  139. function wc_db_check_cookie($cookie){
  140. global $WCDB, $WC;
  141. $user = array();
  142. if(strpos($cookie, ":")!==false){
  143. list($user_id, $session_id) = explode(":", $cookie);
  144. $user_id = $WCDB->escape($user_id);
  145. $session_id = $WCDB->escape($session_id);
  146. $sql = "select * from {$WC['users_table']} where session_id='$session_id' and user_id='$user_id'";
  147. $user = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
  148. }
  149. return $user;
  150. }
  151. /**
  152. * Checks a user name and password
  153. *
  154. * @param $user_name The user name to check
  155. * @param $password The password to check
  156. * @return bool
  157. *
  158. */
  159. function wc_db_check_login($user_name, $password) {
  160. global $WCDB, $WC;
  161. $user_name = $WCDB->escape($user_name);
  162. $password = md5($password).sha1($password);
  163. $sql = "select user_id from {$WC['users_table']} where user_name='$user_name' and password='$password'";
  164. return (int)$WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "user_id");
  165. }
  166. /**
  167. * Saves a post to the database.
  168. * To save an existing post, put the post_id in the array.
  169. *
  170. * @param $post Array of post elements to save
  171. * @return bool
  172. *
  173. */
  174. function wc_db_save_post(&$post){
  175. global $WCDB, $WC;
  176. $clean_arr = array();
  177. $result = false;
  178. if(isset($post["post_id"]) && empty($post["post_id"])) unset($post["post_id"]);
  179. foreach($post as $field=>$value){
  180. switch($field){
  181. case "post_id":
  182. case "user_id":
  183. case "allow_comments":
  184. case "published":
  185. case "post_date":
  186. $clean_arr[$field] = (int)$value;
  187. break;
  188. case "tags":
  189. break;
  190. case "subject":
  191. case "body":
  192. case "uri":
  193. $clean_arr[$field] = $WCDB->escape($value);
  194. break;
  195. default:
  196. trigger_error("Invalid field $field sent to ".__FUNCTION__.".", E_USER_WARNING);
  197. continue;
  198. }
  199. }
  200. if(!empty($post["post_id"])){
  201. // build an update
  202. $sql = "update {$WC['posts_table']} set ";
  203. foreach($clean_arr as $field=>$value){
  204. if($field!="post_id"){
  205. $sql.= "$field = '$value',";
  206. }
  207. }
  208. $sql = substr($sql, 0, -1); // trim the last comma
  209. $sql.= " where post_id=".$post["post_id"];
  210. $result = $WCDB->query($sql);
  211. if($result && isset($post["tags"])){
  212. $sql = "delete from {$WC['tags_table']} where post_id=".$post["post_id"];
  213. $WCDB->query($sql);
  214. $tag_arr = explode(",", $post["tags"]);
  215. foreach($tag_arr as $tag){
  216. $tag = trim($tag);
  217. if(empty($tag)) continue;
  218. $sql = "insert into {$WC['tags_table']} values (".$post["post_id"].", '".$WCDB->escape($tag)."')";
  219. $WCDB->query($sql);
  220. }
  221. }
  222. } else {
  223. // build an insert
  224. if(isset($post["post_id"])) unset($post["post_id"]);
  225. if(!isset($post["body"])) $post["body"] = "";
  226. $fields = "";
  227. $values = "";
  228. foreach($clean_arr as $field=>$value){
  229. $fields.="$field,";
  230. $values.="'$value',";
  231. }
  232. $fields = substr($fields, 0, -1); // trim the last comma
  233. $values = substr($values, 0, -1); // trim the last comma
  234. $sql = "insert into {$WC['posts_table']} ($fields) values ($values)";
  235. $post_id = $WCDB->query_fetch($sql, WC_DB_FETCH_INSERT_ID);
  236. $post["post_id"] = $post_id;
  237. if($post_id && isset($post["tags"])){
  238. $result = $post_id;
  239. $tag_arr = explode(",", $post["tags"]);
  240. foreach($tag_arr as $tag){
  241. $tag = trim($tag);
  242. if(empty($tag)) continue;
  243. $sql = "replace into {$WC['tags_table']} values (".$post_id.", '".$WCDB->escape($tag)."')";
  244. $WCDB->query($sql);
  245. }
  246. }
  247. }
  248. // update uri in uri lookup
  249. if(isset($clean_arr["uri"])){
  250. $sql = "update {$WC['uri_lookup_table']} set current=0 where type='post' and object_id=".$post["post_id"];
  251. $WCDB->query($sql);
  252. $sql = "replace into {$WC['uri_lookup_table']} set uri='".$clean_arr["uri"]."', current=1, type='post', object_id=".$post["post_id"];
  253. $WCDB->query($sql);
  254. }
  255. return (bool)$result;
  256. }
  257. /**
  258. * Fetch a single post from the database
  259. *
  260. * @param $post_id The id or uri of the post to fetch
  261. * @return array
  262. *
  263. */
  264. function wc_db_get_post($identifier) {
  265. global $WCDB, $WC;
  266. if(is_numeric($identifier)){
  267. $where = "post_id = $identifier";
  268. } else {
  269. $where = "uri = '".$WCDB->escape($identifier)."'";
  270. }
  271. $sql = "select {$WC['posts_table']}.*, {$WC['users_table']}.user_name from {$WC['posts_table']} inner join {$WC['users_table']} using (user_id) where $where";
  272. $post = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
  273. if(!empty($post)){
  274. if(empty($post_id)) $post_id = $post["post_id"];
  275. $sql = "select tag from {$WC['tags_table']} where post_id=".$post_id;
  276. $WCDB->query($sql);
  277. $post["tags"] = array();
  278. while($row = $WCDB->fetch()){
  279. $post["tags"][] = $row["tag"];
  280. }
  281. $post["tags_text"] = implode(", ", $post["tags"]);
  282. // get comment count
  283. $sql = "select count(*) as count from {$WC['comments_table']} where post_id=$post_id and status='APPROVED'";
  284. $post["comment_count"] = (int)$WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "count");
  285. }
  286. return $post;
  287. }
  288. /**
  289. * Gets a post list
  290. *
  291. * @var $start The starting point of the limit to fetch
  292. * @var $limit How many rows to return
  293. * @var $bodies Should the post bodies be returned
  294. * @var $filter A search filter to be applied
  295. * @var $tag Show messages only with these tags
  296. * @var $post_ids Return only these posts
  297. * @var $current Return only post marked as published and with a publish time less than now
  298. */
  299. function wc_db_get_post_list($start=false, $limit=false, $bodies=false, $filter="", $tag="", $post_ids=false, $current=true) {
  300. global $WCDB, $WC;
  301. $bodies = (bool)$bodies;
  302. if(!$bodies){
  303. $fields = "post_id, subject, post_date, user_id";
  304. } else {
  305. $fields = "*";
  306. }
  307. $sql = "select SQL_CALC_FOUND_ROWS $fields from {$WC['posts_table']} ";
  308. $where = array();
  309. if($tag){
  310. $tag = $WCDB->escape((string)$tag);
  311. $sql.= "inner join {$WC['tags_table']} on
  312. {$WC['posts_table']}.post_id={$WC['tags_table']}.post_id and
  313. {$WC['tags_table']}.tag='$tag' ";
  314. }
  315. if($filter) {
  316. $where[] = wc_db_create_like_string(array("subject", "body"), $filter);
  317. }
  318. if($post_ids!=false && is_array($post_ids)){
  319. $WCDB->escape($post_ids, "int");
  320. if(count($post_ids)){
  321. $where[] = "post_id in (".implode(",", $post_ids).")";
  322. }
  323. }
  324. if($current) {
  325. $now = time();
  326. $where[] = "post_date < $now and published=1";
  327. }
  328. if(count($where)){
  329. $sql.= " where ".implode(" and ", $where);
  330. }
  331. $sql.= " order by post_date desc";
  332. if(is_numeric($start) && is_numeric($limit)){
  333. $sql.= " limit $start, $limit";
  334. }
  335. $WCDB->query($sql);
  336. $posts = array();
  337. while($row = $WCDB->fetch()){
  338. // seed comment count and tags
  339. $row["comment_count"] = 0;
  340. $row["tags"] = array();
  341. $posts[$row["post_id"]] = $row;
  342. $user_ids[$row["post_id"]] = $row["user_id"];
  343. }
  344. $sql = "select found_rows() as total";
  345. $total = $WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "total");
  346. if(!empty($posts)){
  347. // get users
  348. $sql = "select user_id, user_name from {$WC['users_table']} where user_id in (".implode(",", $user_ids).")";
  349. $WCDB->query($sql);
  350. while($row = $WCDB->fetch()){
  351. $usernames[$row["user_id"]] = $row["user_name"];
  352. }
  353. foreach($user_ids as $post_id=>$user_id){
  354. $posts[$post_id]["user_name"] = $usernames[$user_id];
  355. }
  356. // get tags
  357. $sql = "select post_id, tag from {$WC['tags_table']} where post_id in (".implode(",", array_keys($posts)).")";
  358. $WCDB->query($sql);
  359. while($row = $WCDB->fetch()){
  360. $posts[$row["post_id"]]["tags"][] = $row["tag"];
  361. }
  362. // get comment count
  363. $sql = "select post_id, count(*) as count from {$WC['comments_table']} where post_id in (".implode(",", array_keys($posts)).") and status='APPROVED' group by post_id";
  364. $WCDB->query($sql);
  365. while($row = $WCDB->fetch()){
  366. if(!empty($row["post_id"])){
  367. $posts[$row["post_id"]]["comment_count"] = $row["count"];
  368. }
  369. }
  370. }
  371. return array($posts, $total);
  372. }
  373. /**
  374. * Deletes a post
  375. *
  376. * @param $post_id The id of the post to be deleted.
  377. * @return bool
  378. *
  379. */
  380. function wc_db_delete_post($post_id) {
  381. global $WCDB, $WC;
  382. $post_id = (int)$post_id;
  383. $sql = "delete from {$WC['posts_table']} where post_id=$post_id";
  384. $res = $WCDB->query($sql);
  385. if($res != false){
  386. $sql = "delete from {$WC['tags_table']} where post_id=$post_id";
  387. $WCDB->query($sql);
  388. }
  389. return (bool)$res;
  390. }
  391. /**
  392. * Gets a list of users from the database
  393. * The funtion returns an array where the first element
  394. * is the users and the second is the total.
  395. *
  396. * @param $start The position in the list to start from
  397. * @param $limit The maximum number of users to return
  398. * @param $filter Options filter value to run against the user list
  399. * @return mixed
  400. *
  401. */
  402. function wc_db_get_user_list($start, $limit, $filter="") {
  403. global $WCDB, $WC;
  404. $start = (int)$start;
  405. $limit = (int)$limit;
  406. $filter = (string)$filter;
  407. $sql = "select SQL_CALC_FOUND_ROWS * from {$WC['users_table']} ";
  408. if($filter) {
  409. $words = preg_split('!\s+!', $filter);
  410. $match = $WCDB->escape("+".implode(" +", $words));
  411. $sql.= "where
  412. match (user_name, first_name, last_name, email)
  413. against ('$match' in boolean mode) ";
  414. }
  415. $sql.= " order by user_name desc limit $start, $limit";
  416. $WCDB->query($sql);
  417. while($row = $WCDB->fetch()){
  418. $users[$row["user_id"]] = $row;
  419. }
  420. $sql = "select found_rows() as total";
  421. $total = $WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "total");
  422. return array($users, $total);
  423. }
  424. /**
  425. * Fetch a single user from the database
  426. *
  427. * @param $user_id The id of the user to fetch
  428. * @return array
  429. *
  430. */
  431. function wc_db_get_user($user_id) {
  432. global $WCDB, $WC;
  433. $user_id = (int)$user_id;
  434. $sql = "select * from {$WC['users_table']} where user_id=".$user_id;
  435. $user = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
  436. return $user;
  437. }
  438. /**
  439. * Saves a user to the database.
  440. * To save an existing user, put the user_id in the array.
  441. *
  442. * @param $user Array of user elements to save
  443. * @return bool
  444. *
  445. */
  446. function wc_db_save_user($user){
  447. global $WCDB, $WC;
  448. $clean_arr = array();
  449. $result = false;
  450. if(isset($user["user_id"]) && empty($user["user_id"])) unset($user["user_id"]);
  451. foreach($user as $field=>$value){
  452. switch($field){
  453. case "user_id":
  454. $clean_arr[$field] = (int)$value;
  455. break;
  456. case "user_name":
  457. case "first_name":
  458. case "last_name":
  459. case "email":
  460. case "about":
  461. case "session_id":
  462. $clean_arr[$field] = $WCDB->escape($value);
  463. break;
  464. case "password":
  465. $value = md5($value).sha1($value);
  466. $clean_arr[$field] = $WCDB->escape($value);
  467. break;
  468. default:
  469. trigger_error("Invalid field $field sent to ".__FUNCTION__.".", E_USER_WARNING);
  470. break;
  471. }
  472. }
  473. if(!empty($user["user_id"])){
  474. // build an update
  475. $sql = "update {$WC['users_table']} set ";
  476. foreach($clean_arr as $field=>$value){
  477. if($field!="user_id"){
  478. $sql.= "$field = '$value',";
  479. }
  480. }
  481. $sql = substr($sql, 0, -1); // trim the last comma
  482. $sql.= " where user_id=".$user["user_id"];
  483. $result = $WCDB->query($sql);
  484. } else {
  485. // build an insert
  486. if(isset($user["user_id"])) unset($user["user_id"]);
  487. if(!isset($user["body"])) $user["body"] = "";
  488. $fields = "";
  489. $values = "";
  490. foreach($clean_arr as $field=>$value){
  491. $fields.="$field,";
  492. $values.="'$value',";
  493. }
  494. $fields = substr($fields, 0, -1); // trim the last comma
  495. $values = substr($values, 0, -1); // trim the last comma
  496. $sql = "insert into {$WC['users_table']} ($fields) values ($values)";
  497. $result = $WCDB->query_fetch($sql, WC_DB_FETCH_INSERT_ID);
  498. }
  499. return (bool)$result;
  500. }
  501. /**
  502. * Deletes a user
  503. *
  504. * @param $user_id The id of the user to be deleted.
  505. * @return bool
  506. *
  507. */
  508. function wc_db_delete_user($user_id) {
  509. global $WCDB, $WC;
  510. $user_id = (int)$user_id;
  511. $sql = "delete from {$WC['users_table']} where user_id=$user_id";
  512. $res = $WCDB->query($sql);
  513. return (bool)$res;
  514. }
  515. /**
  516. * Gets a tag list from the database
  517. * Returned in order of most posts
  518. *
  519. * @param $limit Maximum number of tags to get
  520. * @return array
  521. *
  522. */
  523. function wc_db_get_tags($limit=0) {
  524. global $WCDB, $WC;
  525. $tags = array();
  526. $limit = (int)$limit;
  527. $sql = "select tag, count(*) as post_count from {$WC['tags_table']} group by tag order by post_count desc";
  528. if($limit) $sql.= " limit $limit";
  529. $WCDB->query($sql);
  530. while($rec = $WCDB->fetch()){
  531. $tags[] = $rec;
  532. }
  533. return $tags;
  534. }
  535. /**
  536. * Posts a comment to the database
  537. * To save an existing comment, put the comment_id in the array.
  538. *
  539. * @param $comment Array contianing comment data
  540. * @return mixed
  541. *
  542. */
  543. function wc_db_save_comment($comment) {
  544. global $WCDB, $WC;
  545. // these are required
  546. if(!isset($comment["comment_id"])){
  547. if(empty($comment["comment"])) return false;
  548. if(empty($comment["post_id"])) return false;
  549. if(empty($comment["name"])) return false;
  550. if(empty($comment["comment_date"])) $comment["comment_date"] = time();
  551. }
  552. foreach($comment as $field=>$value){
  553. switch($field){
  554. case "post_id":
  555. case "comment_id":
  556. case "linkback":
  557. $clean_arr[$field] = (int)$value;
  558. break;
  559. case "name":
  560. case "email":
  561. case "url":
  562. case "ip_address":
  563. case "comment":
  564. case "comment_date":
  565. $clean_arr[$field] = $WCDB->escape($value);
  566. break;
  567. case "status":
  568. if($value!='APPROVED' && $value!='UNAPPROVED' && $value!='SPAM'){
  569. $value = 'UNAPPROVED';
  570. }
  571. $clean_arr[$field] = $value;
  572. break;
  573. default:
  574. trigger_error("Invalid field $field sent to ".__FUNCTION__.".", E_USER_WARNING);
  575. break;
  576. }
  577. }
  578. if(isset($clean_arr["comment_id"])){
  579. $fields = "";
  580. foreach($clean_arr as $field=>$value){
  581. if($field!="comment_id"){
  582. if(is_numeric($value)){
  583. $fields.="$field = $value,";
  584. } else {
  585. $fields.="$field = '$value',";
  586. }
  587. }
  588. }
  589. $fields = substr($fields, 0, -1); // trim the last comma
  590. $sql = "update {$WC['comments_table']} set $fields where comment_id=".$clean_arr["comment_id"];
  591. $success = $WCDB->query($sql);
  592. } else {
  593. $fields = "";
  594. $values = "";
  595. foreach($clean_arr as $field=>$value){
  596. $fields.="$field,";
  597. $values.="'$value',";
  598. }
  599. $fields = substr($fields, 0, -1); // trim the last comma
  600. $values = substr($values, 0, -1); // trim the last comma
  601. $sql = "insert into {$WC['comments_table']} ($fields) values ($values)";
  602. $comment_id = $WCDB->query_fetch($sql, WC_DB_FETCH_INSERT_ID);
  603. }
  604. return $comment_id;
  605. }
  606. /**
  607. * Deletes a comment from the database
  608. *
  609. * @param $comment_id Comment's id to delete
  610. * @return bool
  611. *
  612. */
  613. function wc_db_delete_comment($comment_id) {
  614. global $WCDB, $WC;
  615. // these are required
  616. $comment_id = (int)$comment_id;
  617. if(empty($comment_id)) return false;
  618. $sql = "delete from {$WC['comments_table']} where comment_id=$comment_id";
  619. return (bool)$WCDB->query($sql);
  620. }
  621. /**
  622. * Deletes all spam comments from the database
  623. *
  624. * @return bool
  625. *
  626. */
  627. function wc_db_delete_spam() {
  628. global $WCDB, $WC;
  629. $sql = "delete from {$WC['comments_table']} where status='spam'";
  630. return (bool)$WCDB->query($sql);
  631. }
  632. function wc_db_get_comment($comment_id) {
  633. global $WCDB, $WC;
  634. $comment_id = (int)$comment_id;
  635. $sql = "select * from {$WC['comments_table']} where comment_id=$comment_id";
  636. $comment = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
  637. return $comment;
  638. }
  639. function wc_db_get_comments($post_id=false, $status=false, $start=false, $limit=false, $filter=false) {
  640. global $WCDB, $WC;
  641. $sql = "select SQL_CALC_FOUND_ROWS * from {$WC['comments_table']} ";
  642. $order_by = "comment_id desc";
  643. $where = array();
  644. if(is_numeric($post_id)){
  645. $where[] = "post_id=$post_id";
  646. $order_by = "comment_date";
  647. }
  648. if($filter) {
  649. $where[] = wc_db_create_like_string(array("name", "comment", "email"), $filter);
  650. }
  651. if($status!==false){
  652. if(is_array($status)){
  653. foreach($status as &$s){
  654. $s = $WCDB->escape($s);
  655. }
  656. $w = "status in ('".implode("','", $status)."')";
  657. $where[] = $w;
  658. } else {
  659. $where[] = "status='".$WCDB->escape($status)."'";
  660. }
  661. }
  662. if(!empty($where)){
  663. $sql.= " where ".implode(" and ", $where);
  664. }
  665. $sql.= " order by $order_by";
  666. if(is_numeric($start) && is_numeric($limit)){
  667. $sql.= " limit $start, $limit";
  668. }
  669. $comments = $WCDB->query_fetch($sql, WC_DB_FETCH_ALL_ASSOC);
  670. $sql = "select found_rows() as total";
  671. $total = (int)$WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "total");
  672. if(empty($comments)) $comments = array();
  673. return array($comments, $total);
  674. }
  675. /**
  676. * Creates a LIKE clause for a query
  677. *
  678. * @param $fields Fields to be searched
  679. * @param $search The search string provided by the user
  680. * @return string
  681. *
  682. */
  683. function wc_db_create_like_string($fields, $search) {
  684. global $WCDB;
  685. // Surround with spaces so matching is easier.
  686. $search = " $search ";
  687. // Pull out all grouped terms, e.g. (nano mini).
  688. $paren_terms = array();
  689. if (strstr($search, '(')) {
  690. preg_match_all('/ (\-*\(.+?\)) /', $search, $m);
  691. $search = preg_replace('/ \-*\(.+?\) /', ' ', $search);
  692. $paren_terms = $m[1];
  693. }
  694. // Pull out all the double quoted strings,
  695. // e.g. '"iMac DV" or -"iMac DV".
  696. $quoted_terms = array();
  697. if (strstr( $search, '"')) {
  698. preg_match_all('/ (\-*".+?") /', $search, $m);
  699. $search = preg_replace('/ \-*".+?" /', ' ', $search);
  700. $quoted_terms = $m[1];
  701. }
  702. // Finally, pull out the rest words in the string.
  703. $norm_terms = preg_split("/\s+/", $search, 0, PREG_SPLIT_NO_EMPTY);
  704. // Merge all search terms together.
  705. $tokens = array_merge($quoted_terms, $paren_terms, $norm_terms);
  706. $clauses = array();
  707. foreach($tokens as $token){
  708. if(preg_match('!\((.+?)\)!', $token, $match)){
  709. $sub_token = explode(",", $match[1]);
  710. } else {
  711. $sub_token = array($token);
  712. }
  713. $tok_clauses = array();
  714. foreach($sub_token as $sub){
  715. $sub = trim($sub);
  716. if($sub[0]=="-"){
  717. $sub = substr($sub, 1);
  718. $cond = "NOT LIKE";
  719. } else {
  720. $cond = "LIKE";
  721. }
  722. if(preg_match('!"(.+?)"!', $sub, $match)){
  723. $sub = $match[1];
  724. }
  725. $sub = $WCDB->escape($sub);
  726. foreach($fields as $field){
  727. $tok_clauses[] = "$field $cond '%$sub%'";
  728. }
  729. }
  730. $clauses[] = "(".implode(" OR ", $tok_clauses).")";
  731. }
  732. return implode(" AND\n", $clauses);
  733. }
  734. /**
  735. * Fetch a single page from the database
  736. *
  737. * @param $identifier The id or uri of the page to fetch
  738. * @return array
  739. *
  740. */
  741. function wc_db_get_page($identifier) {
  742. global $WCDB, $WC;
  743. if(is_numeric($identifier)){
  744. $where = "page_id = $identifier";
  745. } else {
  746. $where = "uri = '".$WCDB->escape($identifier)."'";
  747. }
  748. $sql = "select {$WC['pages_table']}.* from {$WC['pages_table']} where $where";
  749. $page = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
  750. return $page;
  751. }
  752. /**
  753. * Saves a page to the database.
  754. * To save an existing page, put the page_id in the array.
  755. *
  756. * @param $page Array of page elements to save
  757. * @return bool
  758. *
  759. */
  760. function wc_db_save_page($page){
  761. global $WCDB, $WC;
  762. $clean_arr = array();
  763. $result = false;
  764. if(isset($page["page_id"]) && empty($page["page_id"])) unset($page["page_id"]);
  765. foreach($page as $field=>$value){
  766. switch($field){
  767. case "page_id":
  768. $clean_arr[$field] = (int)$value;
  769. break;
  770. case "nav_label":
  771. case "title":
  772. case "body":
  773. case "uri":
  774. $clean_arr[$field] = $WCDB->escape($value);
  775. break;
  776. default:
  777. trigger_error("Invalid field $field sent to ".__FUNCTION__.".", E_USER_WARNING);
  778. continue;
  779. }
  780. }
  781. if(!empty($page["page_id"])){
  782. // build an update
  783. $sql = "update {$WC['pages_table']} set ";
  784. foreach($clean_arr as $field=>$value){
  785. if($field!="page_id"){
  786. $sql.= "$field = '$value',";
  787. }
  788. }
  789. $sql = substr($sql, 0, -1); // trim the last comma
  790. $sql.= " where page_id=".$page["page_id"];
  791. $result = $WCDB->query($sql);
  792. } else {
  793. // build an insert
  794. if(isset($page["page_id"])) unset($page["page_id"]);
  795. if(!isset($page["body"])) $page["body"] = "";
  796. foreach($clean_arr as $field=>$value){
  797. $fields.="$field,";
  798. $values.="'$value',";
  799. }
  800. $fields = substr($fields, 0, -1); // trim the last comma
  801. $values = substr($values, 0, -1); // trim the last comma
  802. $sql = "insert into {$WC['pages_table']} ($fields) values ($values)";
  803. $page_id = $WCDB->query_fetch($sql, WC_DB_FETCH_INSERT_ID);
  804. if($page_id){
  805. $result = $page_id;
  806. $page["page_id"] = $page_id;
  807. }
  808. }
  809. // update uri in uri lookup
  810. if(isset($clean_arr["uri"])){
  811. $sql = "update {$WC['uri_lookup_table']} set current=0 where type='page' and object_id=".$page["page_id"];
  812. $WCDB->query($sql);
  813. $sql = "replace into {$WC['uri_lookup_table']} set uri='".$clean_arr["uri"]."', current=1, type='page', object_id=".$page["page_id"];
  814. $WCDB->query($sql);
  815. }
  816. return (bool)$result;
  817. }
  818. /**
  819. * Deletes a page
  820. *
  821. * @param $page_id The id of the page to be deleted.
  822. * @return bool
  823. *
  824. */
  825. function wc_db_delete_page($page_id) {
  826. global $WCDB, $WC;
  827. $page_id = (int)$page_id;
  828. $sql = "delete from {$WC['pages_table']} where page_id=$page_id";
  829. $res = $WCDB->query($sql);
  830. return (bool)$res;
  831. }
  832. /**
  833. * Function description
  834. * The funtion returns an array where the first element
  835. * is the pages and the second is the total.
  836. *
  837. * @param $var desctription
  838. * @return mixed
  839. *
  840. */
  841. function wc_db_get_page_list($start=false, $limit=false, $bodies=false, $filter="", $page_ids=false) {
  842. global $WCDB, $WC;
  843. $bodies = (bool)$bodies;
  844. if(!$bodies){
  845. $fields = "page_id, title";
  846. } else {
  847. $fields = "*";
  848. }
  849. $sql = "select SQL_CALC_FOUND_ROWS $fields from {$WC['pages_table']} ";
  850. $where = array();
  851. if($filter) {
  852. $words = preg_split('!\s+!', $filter);
  853. $match = $WCDB->escape("+".implode(" +", $words));
  854. $where[] = "match (title, body) against ('$match' in boolean mode)";
  855. }
  856. if($page_ids!=false && is_array($page_ids)){
  857. $WCDB->escape($page_ids, "int");
  858. if(count($page_ids)){
  859. $where[] = "page_id in (".implode(",", $page_ids).")";
  860. }
  861. }
  862. if(count($where)){
  863. $sql.= " where ".implode(" and ", $where);
  864. }
  865. $sql.= "order by title";
  866. if(is_numeric($start) && is_numeric($limit)){
  867. $sql.= " limit $start, $limit";
  868. }
  869. $WCDB->query($sql);
  870. while($row = $WCDB->fetch()){
  871. $pages[$row["page_id"]] = $row;
  872. }
  873. $sql = "select found_rows() as total";
  874. $total = $WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "total");
  875. return array($pages, $total);
  876. }
  877. /**
  878. * Gets a page list from the database
  879. * Returned in order of nav_label
  880. *
  881. * @param $limit Maximum number of pages to get
  882. * @return array
  883. *
  884. */
  885. function wc_db_get_nav_pages($limit=0) {
  886. global $WCDB, $WC;
  887. $pages = array();
  888. $limit = (int)$limit;
  889. $sql = "select page_id, nav_label, uri from {$WC['pages_table']} order by nav_label";
  890. if($limit) $sql.= " limit $limit";
  891. $WCDB->query($sql);
  892. while($rec = $WCDB->fetch()){
  893. $pages[] = $rec;
  894. }
  895. return $pages;
  896. }
  897. /**
  898. * Looks up a URI in the database
  899. *
  900. * @param $uri URI to find
  901. * @return array
  902. *
  903. */
  904. function wc_db_lookup_uri($uri) {
  905. global $WCDB, $WC;
  906. $sql = "select object_id, type, current from {$WC['uri_lookup_table']} where uri='".$WCDB->escape($uri)."'";
  907. $uri_data = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
  908. if(!empty($uri_data["object_id"]) && $uri_data["current"]!=1){
  909. $sql = "select uri from {$WC['uri_lookup_table']} where object_id=".$uri_data["object_id"]." and current=1";
  910. $uri_data["current_uri"] = $WCDB->query_fetch($sql, WC_DB_FETCH_FIELD);
  911. }
  912. return $uri_data;
  913. }
  914. ?>