PageRenderTime 37ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-contentold/plugins/nextgen-gallery/lib/ngg-db.php

https://bitbucket.org/zachisit/zachis.it-m
PHP | 1111 lines | 516 code | 211 blank | 384 comment | 87 complexity | 0c5a28882b1ab94d95d87cf0e5182887 MD5 | raw file
  1. <?php
  2. if ( !class_exists('nggdb') ) :
  3. /**
  4. * NextGEN Gallery Database Class
  5. *
  6. * @author Alex Rabe, Vincent Prat
  7. *
  8. * @since 1.0.0
  9. */
  10. class nggdb {
  11. /**
  12. * Holds the list of all galleries
  13. *
  14. * @since 1.1.0
  15. * @access public
  16. * @var object|array
  17. */
  18. var $galleries = false;
  19. /**
  20. * Holds the list of all images
  21. *
  22. * @since 1.3.0
  23. * @access public
  24. * @var object|array
  25. */
  26. var $images = false;
  27. /**
  28. * Holds the list of all albums
  29. *
  30. * @since 1.3.0
  31. * @access public
  32. * @var object|array
  33. */
  34. var $albums = false;
  35. /**
  36. * The array for the pagination
  37. *
  38. * @since 1.1.0
  39. * @access public
  40. * @var array
  41. */
  42. var $paged = false;
  43. /**
  44. * PHP4 compatibility layer for calling the PHP5 constructor.
  45. *
  46. */
  47. function nggdb() {
  48. return $this->__construct();
  49. }
  50. /**
  51. * Init the Database Abstraction layer for NextGEN Gallery
  52. *
  53. */
  54. function __construct() {
  55. global $wpdb;
  56. $this->galleries = array();
  57. $this->images = array();
  58. $this->albums = array();
  59. $this->paged = array();
  60. register_shutdown_function(array(&$this, '__destruct'));
  61. }
  62. /**
  63. * PHP5 style destructor and will run when database object is destroyed.
  64. *
  65. * @return bool Always true
  66. */
  67. function __destruct() {
  68. return true;
  69. }
  70. /**
  71. * Get all the album and unserialize the content
  72. *
  73. * @since 1.3.0
  74. * @param string $order_by
  75. * @param string $order_dir
  76. * @param int $limit number of albums, 0 shows all albums
  77. * @param int $start the start index for paged albums
  78. * @return array $album
  79. */
  80. function find_all_album( $order_by = 'id', $order_dir = 'ASC', $limit = 0, $start = 0) {
  81. global $wpdb;
  82. $order_dir = ( $order_dir == 'DESC') ? 'DESC' : 'ASC';
  83. $limit_by = ( $limit > 0 ) ? 'LIMIT ' . intval($start) . ',' . intval($limit) : '';
  84. $this->albums = $wpdb->get_results("SELECT * FROM $wpdb->nggalbum ORDER BY {$order_by} {$order_dir} {$limit_by}" , OBJECT_K );
  85. if ( !$this->albums )
  86. return array();
  87. foreach ($this->albums as $key => $value) {
  88. $this->albums[$key]->galleries = empty ($this->albums[$key]->sortorder) ? array() : (array) unserialize($this->albums[$key]->sortorder) ;
  89. $this->albums[$key]->name = stripslashes( $this->albums[$key]->name );
  90. $this->albums[$key]->albumdesc = stripslashes( $this->albums[$key]->albumdesc );
  91. wp_cache_add($key, $this->albums[$key], 'ngg_album');
  92. }
  93. return $this->albums;
  94. }
  95. /**
  96. * Get all the galleries
  97. *
  98. * @param string $order_by
  99. * @param string $order_dir
  100. * @param bool $counter (optional) Select true when you need to count the images
  101. * @param int $limit number of paged galleries, 0 shows all galleries
  102. * @param int $start the start index for paged galleries
  103. * @param bool $exclude
  104. * @return array $galleries
  105. */
  106. function find_all_galleries($order_by = 'gid', $order_dir = 'ASC', $counter = false, $limit = 0, $start = 0, $exclude = true) {
  107. global $wpdb;
  108. // Check for the exclude setting
  109. $exclude_clause = ($exclude) ? ' AND exclude<>1 ' : '';
  110. $order_dir = ( $order_dir == 'DESC') ? 'DESC' : 'ASC';
  111. $limit_by = ( $limit > 0 ) ? 'LIMIT ' . intval($start) . ',' . intval($limit) : '';
  112. $this->galleries = $wpdb->get_results( "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->nggallery ORDER BY {$order_by} {$order_dir} {$limit_by}", OBJECT_K );
  113. // Count the number of galleries and calculate the pagination
  114. if ($limit > 0) {
  115. $this->paged['total_objects'] = intval ( $wpdb->get_var( "SELECT FOUND_ROWS()" ) );
  116. $this->paged['objects_per_page'] = max ( count( $this->galleries ), $limit );
  117. $this->paged['max_objects_per_page'] = ( $limit > 0 ) ? ceil( $this->paged['total_objects'] / intval($limit)) : 1;
  118. }
  119. if ( !$this->galleries )
  120. return array();
  121. // get the galleries information
  122. foreach ($this->galleries as $key => $value) {
  123. $galleriesID[] = $key;
  124. // init the counter values
  125. $this->galleries[$key]->counter = 0;
  126. $this->galleries[$key]->title = stripslashes($this->galleries[$key]->title);
  127. $this->galleries[$key]->galdesc = stripslashes($this->galleries[$key]->galdesc);
  128. $this->galleries[$key]->abspath = WINABSPATH . $this->galleries[$key]->path;
  129. wp_cache_add($key, $this->galleries[$key], 'ngg_gallery');
  130. }
  131. // if we didn't need to count the images then stop here
  132. if ( !$counter )
  133. return $this->galleries;
  134. // get the counter values
  135. $picturesCounter = $wpdb->get_results('SELECT galleryid, COUNT(*) as counter FROM '.$wpdb->nggpictures.' WHERE galleryid IN (\''.implode('\',\'', $galleriesID).'\') ' . $exclude_clause . ' GROUP BY galleryid', OBJECT_K);
  136. if ( !$picturesCounter )
  137. return $this->galleries;
  138. // add the counter to the gallery objekt
  139. foreach ($picturesCounter as $key => $value) {
  140. $this->galleries[$value->galleryid]->counter = $value->counter;
  141. wp_cache_set($value->galleryid, $this->galleries[$value->galleryid], 'ngg_gallery');
  142. }
  143. return $this->galleries;
  144. }
  145. /**
  146. * Get a gallery given its ID
  147. *
  148. * @param int|string $id or $slug
  149. * @return A nggGallery object (null if not found)
  150. */
  151. function find_gallery( $id ) {
  152. global $wpdb;
  153. if( is_numeric($id) ) {
  154. if ( $gallery = wp_cache_get($id, 'ngg_gallery') )
  155. return $gallery;
  156. $gallery = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->nggallery WHERE gid = %d", $id ) );
  157. } else
  158. $gallery = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->nggallery WHERE slug = %s", $id ) );
  159. // Build the object from the query result
  160. if ($gallery) {
  161. // it was a bad idea to use a object, stripslashes_deep() could not used here, learn from it
  162. $gallery->title = stripslashes($gallery->title);
  163. $gallery->galdesc = stripslashes($gallery->galdesc);
  164. $gallery->abspath = WINABSPATH . $gallery->path;
  165. //TODO:Possible failure , $id could be a number or name
  166. wp_cache_add($id, $gallery, 'ngg_gallery');
  167. return $gallery;
  168. } else
  169. return false;
  170. }
  171. /**
  172. * This function return all information about the gallery and the images inside
  173. *
  174. * @param int|string $id or $name
  175. * @param string $order_by
  176. * @param string $order_dir (ASC |DESC)
  177. * @param bool $exclude
  178. * @param int $limit number of paged galleries, 0 shows all galleries
  179. * @param int $start the start index for paged galleries
  180. * @param bool $json remove the key for associative array in json request
  181. * @return An array containing the nggImage objects representing the images in the gallery.
  182. */
  183. function get_gallery($id, $order_by = 'sortorder', $order_dir = 'ASC', $exclude = true, $limit = 0, $start = 0, $json = false) {
  184. global $wpdb;
  185. // init the gallery as empty array
  186. $gallery = array();
  187. $i = 0;
  188. // Check for the exclude setting
  189. $exclude_clause = ($exclude) ? ' AND tt.exclude<>1 ' : '';
  190. // Say no to any other value
  191. $order_dir = ( $order_dir == 'DESC') ? 'DESC' : 'ASC';
  192. $order_by = ( empty($order_by) ) ? 'sortorder' : $order_by;
  193. // Should we limit this query ?
  194. $limit_by = ( $limit > 0 ) ? 'LIMIT ' . intval($start) . ',' . intval($limit) : '';
  195. // Query database
  196. if( is_numeric($id) )
  197. $result = $wpdb->get_results( $wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS tt.*, t.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE t.gid = %d {$exclude_clause} ORDER BY tt.{$order_by} {$order_dir} {$limit_by}", $id ), OBJECT_K );
  198. else
  199. $result = $wpdb->get_results( $wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS tt.*, t.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE t.slug = %s {$exclude_clause} ORDER BY tt.{$order_by} {$order_dir} {$limit_by}", $id ), OBJECT_K );
  200. // Count the number of images and calculate the pagination
  201. if ($limit > 0) {
  202. $this->paged['total_objects'] = intval ( $wpdb->get_var( "SELECT FOUND_ROWS()" ) );
  203. $this->paged['objects_per_page'] = max ( count( $result ), $limit );
  204. $this->paged['max_objects_per_page'] = ( $limit > 0 ) ? ceil( $this->paged['total_objects'] / intval($limit)) : 1;
  205. }
  206. // Build the object
  207. if ($result) {
  208. // Now added all image data
  209. foreach ($result as $key => $value) {
  210. // due to a browser bug we need to remove the key for associative array for json request
  211. // (see http://code.google.com/p/chromium/issues/detail?id=883)
  212. if ($json) $key = $i++;
  213. $gallery[$key] = new nggImage( $value ); // keep in mind each request require 8-16 kb memory usage
  214. }
  215. }
  216. // Could not add to cache, the structure is different to find_gallery() cache_add, need rework
  217. //wp_cache_add($id, $gallery, 'ngg_gallery');
  218. return $gallery;
  219. }
  220. /**
  221. * This function return all information about the gallery and the images inside
  222. *
  223. * @param int|string $id or $name
  224. * @param string $orderby
  225. * @param string $order (ASC |DESC)
  226. * @param bool $exclude
  227. * @return An array containing the nggImage objects representing the images in the gallery.
  228. */
  229. function get_ids_from_gallery($id, $order_by = 'sortorder', $order_dir = 'ASC', $exclude = true) {
  230. global $wpdb;
  231. // Check for the exclude setting
  232. $exclude_clause = ($exclude) ? ' AND tt.exclude<>1 ' : '';
  233. // Say no to any other value
  234. $order_dir = ( $order_dir == 'DESC') ? 'DESC' : 'ASC';
  235. $order_by = ( empty($order_by) ) ? 'sortorder' : $order_by;
  236. // Query database
  237. if( is_numeric($id) )
  238. $result = $wpdb->get_col( $wpdb->prepare( "SELECT tt.pid FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE t.gid = %d $exclude_clause ORDER BY tt.{$order_by} $order_dir", $id ) );
  239. else
  240. $result = $wpdb->get_col( $wpdb->prepare( "SELECT tt.pid FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE t.slug = %s $exclude_clause ORDER BY tt.{$order_by} $order_dir", $id ) );
  241. return $result;
  242. }
  243. /**
  244. * Delete a gallery AND all the pictures associated to this gallery!
  245. *
  246. * @id The gallery ID
  247. */
  248. function delete_gallery( $id ) {
  249. global $wpdb;
  250. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->nggpictures WHERE galleryid = %d", $id) );
  251. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->nggallery WHERE gid = %d", $id) );
  252. wp_cache_delete($id, 'ngg_gallery');
  253. //TODO:Remove all tag relationship
  254. return true;
  255. }
  256. /**
  257. * Get an album given its ID
  258. *
  259. * @id The album ID or name
  260. * @return A nggGallery object (false if not found)
  261. */
  262. function find_album( $id ) {
  263. global $wpdb;
  264. // Query database
  265. if ( is_numeric($id) && $id != 0 ) {
  266. if ( $album = wp_cache_get($id, 'ngg_album') )
  267. return $album;
  268. $album = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->nggalbum WHERE id = %d", $id) );
  269. } elseif ( $id == 'all' || (is_numeric($id) && $id == 0) ) {
  270. // init the object and fill it
  271. $album = new stdClass();
  272. $album->id = 'all';
  273. $album->name = __('Album overview','nggallery');
  274. $album->albumdesc = __('Album overview','nggallery');
  275. $album->previewpic = 0;
  276. $album->sortorder = serialize( $wpdb->get_col("SELECT gid FROM $wpdb->nggallery") );
  277. } else {
  278. $album = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->nggalbum WHERE slug = %s", $id) );
  279. }
  280. // Unserialize the galleries inside the album
  281. if ( $album ) {
  282. if ( !empty( $album->sortorder ) )
  283. $album->gallery_ids = unserialize( $album->sortorder );
  284. // it was a bad idea to use a object, stripslashes_deep() could not used here, learn from it
  285. $album->albumdesc = stripslashes($album->albumdesc);
  286. $album->name = stripslashes($album->name);
  287. wp_cache_add($album->id, $album, 'ngg_album');
  288. return $album;
  289. }
  290. return false;
  291. }
  292. /**
  293. * Delete an album
  294. *
  295. * @id The album ID
  296. */
  297. function delete_album( $id ) {
  298. global $wpdb;
  299. $result = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->nggalbum WHERE id = %d", $id) );
  300. wp_cache_delete($id, 'ngg_album');
  301. return $result;
  302. }
  303. /**
  304. * Insert an image in the database
  305. *
  306. * @return the ID of the inserted image
  307. */
  308. function insert_image($gid, $filename, $alttext, $desc, $exclude) {
  309. global $wpdb;
  310. $result = $wpdb->query(
  311. "INSERT INTO $wpdb->nggpictures (galleryid, filename, description, alttext, exclude) VALUES "
  312. . "('$gid', '$filename', '$desc', '$alttext', '$exclude');");
  313. $pid = (int) $wpdb->insert_id;
  314. wp_cache_delete($gid, 'ngg_gallery');
  315. return $pid;
  316. }
  317. /**
  318. * nggdb::update_image() - Update an image in the database
  319. *
  320. * @param int $pid id of the image
  321. * @param (optional) string|int $galleryid
  322. * @param (optional) string $filename
  323. * @param (optional) string $description
  324. * @param (optional) string $alttext
  325. * @param (optional) int $exclude (0 or 1)
  326. * @param (optional) int $sortorder
  327. * @return bool result of update query
  328. */
  329. function update_image($pid, $galleryid = false, $filename = false, $description = false, $alttext = false, $exclude = false, $sortorder = false) {
  330. global $wpdb;
  331. $sql = array();
  332. $pid = (int) $pid;
  333. // slug must be unique, we use the alttext for that
  334. $slug = nggdb::get_unique_slug( sanitize_title( $alttext ), 'image' );
  335. $update = array(
  336. 'image_slug' => $slug,
  337. 'galleryid' => $galleryid,
  338. 'filename' => $filename,
  339. 'description' => $description,
  340. 'alttext' => $alttext,
  341. 'exclude' => $exclude,
  342. 'sortorder' => $sortorder);
  343. // create the sql parameter "name = value"
  344. foreach ($update as $key => $value)
  345. if ($value !== false)
  346. $sql[] = $key . " = '" . $value . "'";
  347. // create the final string
  348. $sql = implode(', ', $sql);
  349. if ( !empty($sql) && $pid != 0)
  350. $result = $wpdb->query( "UPDATE $wpdb->nggpictures SET $sql WHERE pid = $pid" );
  351. wp_cache_delete($pid, 'ngg_image');
  352. return $result;
  353. }
  354. /**
  355. * nggdb::update_gallery() - Update an gallery in the database
  356. *
  357. * @since V1.7.0
  358. * @param int $id id of the gallery
  359. * @param (optional) string $title or name of the gallery
  360. * @param (optional) string $path
  361. * @param (optional) string $description
  362. * @param (optional) int $pageid
  363. * @param (optional) int $previewpic
  364. * @param (optional) int $author
  365. * @return bool result of update query
  366. */
  367. function update_gallery($id, $name = false, $path = false, $title = false, $description = false, $pageid = false, $previewpic = false, $author = false) {
  368. global $wpdb;
  369. $sql = array();
  370. $id = (int) $id;
  371. // slug must be unique, we use the title for that
  372. $slug = nggdb::get_unique_slug( sanitize_title( $title ), 'gallery' );
  373. $update = array(
  374. 'name' => $name,
  375. 'slug' => $slug,
  376. 'path' => $path,
  377. 'title' => $title,
  378. 'galdesc' => $description,
  379. 'pageid' => $pageid,
  380. 'previewpic' => $previewpic,
  381. 'author' => $author);
  382. // create the sql parameter "name = value"
  383. foreach ($update as $key => $value)
  384. if ($value !== false)
  385. $sql[] = $key . " = '" . $value . "'";
  386. // create the final string
  387. $sql = implode(', ', $sql);
  388. if ( !empty($sql) && $id != 0)
  389. $result = $wpdb->query( "UPDATE $wpdb->nggallery SET $sql WHERE gid = $id" );
  390. wp_cache_delete($id, 'ngg_gallery');
  391. return $result;
  392. }
  393. /**
  394. * nggdb::update_album() - Update an album in the database
  395. *
  396. * @since V1.7.0
  397. * @param int $ id id of the album
  398. * @param (optional) string $title
  399. * @param (optional) int $previewpic
  400. * @param (optional) string $description
  401. * @param (optional) serialized array $sortorder
  402. * @param (optional) int $pageid
  403. * @return bool result of update query
  404. */
  405. function update_album($id, $name = false, $previewpic = false, $description = false, $sortorder = false, $pageid = false ) {
  406. global $wpdb;
  407. $sql = array();
  408. $id = (int) $id;
  409. // slug must be unique, we use the title for that
  410. $slug = nggdb::get_unique_slug( sanitize_title( $name ), 'album' );
  411. $update = array(
  412. 'name' => $name,
  413. 'slug' => $slug,
  414. 'previewpic' => $previewpic,
  415. 'albumdesc' => $description,
  416. 'sortorder' => $sortorder,
  417. 'pageid' => $pageid);
  418. // create the sql parameter "name = value"
  419. foreach ($update as $key => $value)
  420. if ($value !== false)
  421. $sql[] = $key . " = '" . $value . "'";
  422. // create the final string
  423. $sql = implode(', ', $sql);
  424. if ( !empty($sql) && $id != 0)
  425. $result = $wpdb->query( "UPDATE $wpdb->nggalbum SET $sql WHERE id = $id" );
  426. wp_cache_delete($id, 'ngg_album');
  427. return $result;
  428. }
  429. /**
  430. * Get an image given its ID
  431. *
  432. * @param int|string The image ID or Slug
  433. * @return object A nggImage object representing the image (false if not found)
  434. */
  435. function find_image( $id ) {
  436. global $wpdb;
  437. if( is_numeric($id) ) {
  438. if ( $image = wp_cache_get($id, 'ngg_image') )
  439. return $image;
  440. $result = $wpdb->get_row( $wpdb->prepare( "SELECT tt.*, t.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE tt.pid = %d ", $id ) );
  441. } else
  442. $result = $wpdb->get_row( $wpdb->prepare( "SELECT tt.*, t.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE tt.image_slug = %s ", $id ) );
  443. // Build the object from the query result
  444. if ($result) {
  445. $image = new nggImage($result);
  446. return $image;
  447. }
  448. return false;
  449. }
  450. /**
  451. * Get images given a list of IDs
  452. *
  453. * @param $pids array of picture_ids
  454. * @return An array of nggImage objects representing the images
  455. */
  456. function find_images_in_list( $pids, $exclude = false, $order = 'ASC' ) {
  457. global $wpdb;
  458. $result = array();
  459. // Check for the exclude setting
  460. $exclude_clause = ($exclude) ? ' AND t.exclude <> 1 ' : '';
  461. // Check for the exclude setting
  462. $order_clause = ($order == 'RAND') ? 'ORDER BY rand() ' : ' ORDER BY t.pid ASC' ;
  463. if ( is_array($pids) ) {
  464. $id_list = "'" . implode("', '", $pids) . "'";
  465. // Save Query database
  466. $images = $wpdb->get_results("SELECT t.*, tt.* FROM $wpdb->nggpictures AS t INNER JOIN $wpdb->nggallery AS tt ON t.galleryid = tt.gid WHERE t.pid IN ($id_list) $exclude_clause $order_clause", OBJECT_K);
  467. // Build the image objects from the query result
  468. if ($images) {
  469. foreach ($images as $key => $image)
  470. $result[$key] = new nggImage( $image );
  471. }
  472. }
  473. return $result;
  474. }
  475. /**
  476. * Add an image to the database
  477. *
  478. * @since V1.4.0
  479. * @param int $pid id of the gallery
  480. * @param (optional) string|int $galleryid
  481. * @param (optional) string $filename
  482. * @param (optional) string $description
  483. * @param (optional) string $alttext
  484. * @param (optional) array $meta data
  485. * @param (optional) int $post_id (required for sync with WP media lib)
  486. * @param (optional) string $imagedate
  487. * @param (optional) int $exclude (0 or 1)
  488. * @param (optional) int $sortorder
  489. * @return bool result of the ID of the inserted image
  490. */
  491. function add_image( $id = false, $filename = false, $description = '', $alttext = '', $meta_data = false, $post_id = 0, $imagedate = '0000-00-00 00:00:00', $exclude = 0, $sortorder = 0 ) {
  492. global $wpdb;
  493. if ( is_array($meta_data) )
  494. $meta_data = serialize($meta_data);
  495. // slug must be unique, we use the alttext for that
  496. $slug = nggdb::get_unique_slug( sanitize_title( $alttext ), 'image' );
  497. // Add the image
  498. if ( false === $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->nggpictures (image_slug, galleryid, filename, description, alttext, meta_data, post_id, imagedate, exclude, sortorder)
  499. VALUES (%s, %d, %s, %s, %s, %s, %d, %s, %d, %d)", $slug, $id, $filename, $description, $alttext, $meta_data, $post_id, $imagedate, $exclude, $sortorder ) ) ) {
  500. return false;
  501. }
  502. $imageID = (int) $wpdb->insert_id;
  503. // Remove from cache the galley, needs to be rebuild now
  504. wp_cache_delete( $id, 'ngg_gallery');
  505. //and give me the new id
  506. return $imageID;
  507. }
  508. /**
  509. * Add an album to the database
  510. *
  511. * @since V1.7.0
  512. * @param (optional) string $title
  513. * @param (optional) int $previewpic
  514. * @param (optional) string $description
  515. * @param (optional) serialized array $sortorder
  516. * @param (optional) int $pageid
  517. * @return bool result of the ID of the inserted album
  518. */
  519. function add_album( $name = false, $previewpic = 0, $description = '', $sortorder = 0, $pageid = 0 ) {
  520. global $wpdb;
  521. // name must be unique, we use the title for that
  522. $slug = nggdb::get_unique_slug( sanitize_title( $name ), 'album' );
  523. // Add the album
  524. if ( false === $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->nggalbum (name, slug, previewpic, albumdesc, sortorder, pageid)
  525. VALUES (%s, %s, %d, %s, %s, %d)", $name, $slug, $previewpic, $description, $sortorder, $pageid ) ) ) {
  526. return false;
  527. }
  528. $albumID = (int) $wpdb->insert_id;
  529. //and give me the new id
  530. return $albumID;
  531. }
  532. /**
  533. * Add an gallery to the database
  534. *
  535. * @since V1.7.0
  536. * @param (optional) string $title or name of the gallery
  537. * @param (optional) string $path
  538. * @param (optional) string $description
  539. * @param (optional) int $pageid
  540. * @param (optional) int $previewpic
  541. * @param (optional) int $author
  542. * @return bool result of the ID of the inserted gallery
  543. */
  544. function add_gallery( $title = '', $path = '', $description = '', $pageid = 0, $previewpic = 0, $author = 0 ) {
  545. global $wpdb;
  546. // slug must be unique, we use the title for that
  547. $slug = nggdb::get_unique_slug( sanitize_title( $title ), 'gallery' );
  548. // Note : The field 'name' is deprecated, it's currently kept only for compat reason with older shortcodes, we copy the slug into this field
  549. if ( false === $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->nggallery (name, slug, path, title, galdesc, pageid, previewpic, author)
  550. VALUES (%s, %s, %s, %s, %s, %d, %d, %d)", $slug, $slug, $path, $title, $description, $pageid, $previewpic, $author ) ) ) {
  551. return false;
  552. }
  553. $galleryID = (int) $wpdb->insert_id;
  554. //and give me the new id
  555. return $galleryID;
  556. }
  557. /**
  558. * Delete an image entry from the database
  559. * @param integer $id is the Image ID
  560. */
  561. function delete_image( $id ) {
  562. global $wpdb;
  563. // Delete the image
  564. $result = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->nggpictures WHERE pid = %d", $id) );
  565. // Delete tag references
  566. wp_delete_object_term_relationships( $id, 'ngg_tag');
  567. // Remove from cache
  568. wp_cache_delete( $id, 'ngg_image');
  569. return $result;
  570. }
  571. /**
  572. * Get the last images registered in the database with a maximum number of $limit results
  573. *
  574. * @param integer $page start offset as page number (0,1,2,3,4...)
  575. * @param integer $limit the number of result
  576. * @param bool $exclude do not show exluded images
  577. * @param int $galleryId Only look for images with this gallery id, or in all galleries if id is 0
  578. * @param string $orderby is one of "id" (default, order by pid), "date" (order by exif date), sort (order by user sort order)
  579. * @return
  580. */
  581. function find_last_images($page = 0, $limit = 30, $exclude = true, $galleryId = 0, $orderby = "id") {
  582. global $wpdb;
  583. // Check for the exclude setting
  584. $exclude_clause = ($exclude) ? ' AND exclude<>1 ' : '';
  585. // a limit of 0 makes no sense
  586. $limit = ($limit == 0) ? 30 : $limit;
  587. // calculate the offset based on the pagr number
  588. $offset = (int) $page * $limit;
  589. $galleryId = (int) $galleryId;
  590. $gallery_clause = ($galleryId === 0) ? '' : ' AND galleryid = ' . $galleryId . ' ';
  591. // default order by pid
  592. $order = 'pid DESC';
  593. switch ($orderby) {
  594. case 'date':
  595. $order = 'imagedate DESC';
  596. break;
  597. case 'sort':
  598. $order = 'sortorder ASC';
  599. break;
  600. }
  601. $result = array();
  602. $gallery_cache = array();
  603. // Query database
  604. $images = $wpdb->get_results("SELECT * FROM $wpdb->nggpictures WHERE 1=1 $exclude_clause $gallery_clause ORDER BY $order LIMIT $offset, $limit");
  605. // Build the object from the query result
  606. if ($images) {
  607. foreach ($images as $key => $image) {
  608. // cache a gallery , so we didn't need to lookup twice
  609. if (!array_key_exists($image->galleryid, $gallery_cache))
  610. $gallery_cache[$image->galleryid] = nggdb::find_gallery($image->galleryid);
  611. // Join gallery information with picture information
  612. foreach ($gallery_cache[$image->galleryid] as $index => $value)
  613. $image->$index = $value;
  614. // Now get the complete image data
  615. $result[$key] = new nggImage( $image );
  616. }
  617. }
  618. return $result;
  619. }
  620. /**
  621. * nggdb::get_random_images() - Get an random image from one ore more gally
  622. *
  623. * @param integer $number of images
  624. * @param integer $galleryID optional a Gallery
  625. * @return A nggImage object representing the image (null if not found)
  626. */
  627. function get_random_images($number = 1, $galleryID = 0) {
  628. global $wpdb;
  629. $number = (int) $number;
  630. $galleryID = (int) $galleryID;
  631. $images = array();
  632. // Query database
  633. if ($galleryID == 0)
  634. $result = $wpdb->get_results("SELECT t.*, tt.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE tt.exclude != 1 ORDER by rand() limit $number");
  635. else
  636. $result = $wpdb->get_results("SELECT t.*, tt.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE t.gid = $galleryID AND tt.exclude != 1 ORDER by rand() limit {$number}");
  637. // Return the object from the query result
  638. if ($result) {
  639. foreach ($result as $image) {
  640. $images[] = new nggImage( $image );
  641. }
  642. return $images;
  643. }
  644. return null;
  645. }
  646. /**
  647. * Get all the images from a given album
  648. *
  649. * @param object|int $album The album object or the id
  650. * @param string $order_by
  651. * @param string $order_dir
  652. * @param bool $exclude
  653. * @return An array containing the nggImage objects representing the images in the album.
  654. */
  655. function find_images_in_album($album, $order_by = 'galleryid', $order_dir = 'ASC', $exclude = true) {
  656. global $wpdb;
  657. if ( !is_object($album) )
  658. $album = nggdb::find_album( $album );
  659. // Get gallery list
  660. $gallery_list = implode(',', $album->gallery_ids);
  661. // Check for the exclude setting
  662. $exclude_clause = ($exclude) ? ' AND tt.exclude<>1 ' : '';
  663. // Say no to any other value
  664. $order_dir = ( $order_dir == 'DESC') ? 'DESC' : 'ASC';
  665. $order_by = ( empty($order_by) ) ? 'galleryid' : $order_by;
  666. $result = $wpdb->get_results("SELECT t.*, tt.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE tt.galleryid IN ($gallery_list) $exclude_clause ORDER BY tt.$order_by $order_dir");
  667. // Return the object from the query result
  668. if ($result) {
  669. foreach ($result as $image) {
  670. $images[] = new nggImage( $image );
  671. }
  672. return $images;
  673. }
  674. return null;
  675. }
  676. /**
  677. * search for images and return the result
  678. *
  679. * @since 1.3.0
  680. * @param string $request
  681. * @param int $limit number of results, 0 shows all results
  682. * @return Array Result of the request
  683. */
  684. function search_for_images( $request, $limit = 0 ) {
  685. global $wpdb;
  686. // If a search pattern is specified, load the posts that match
  687. if ( !empty($request) ) {
  688. // added slashes screw with quote grouping when done early, so done later
  689. $request = stripslashes($request);
  690. // split the words it a array if seperated by a space or comma
  691. preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $request, $matches);
  692. $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
  693. $n = '%';
  694. $searchand = '';
  695. $search = '';
  696. foreach( (array) $search_terms as $term) {
  697. $term = addslashes_gpc($term);
  698. $search .= "{$searchand}((tt.description LIKE '{$n}{$term}{$n}') OR (tt.alttext LIKE '{$n}{$term}{$n}') OR (tt.filename LIKE '{$n}{$term}{$n}'))";
  699. $searchand = ' AND ';
  700. }
  701. $term = $wpdb->escape($request);
  702. if (count($search_terms) > 1 && $search_terms[0] != $request )
  703. $search .= " OR (tt.description LIKE '{$n}{$term}{$n}') OR (tt.alttext LIKE '{$n}{$term}{$n}') OR (tt.filename LIKE '{$n}{$term}{$n}')";
  704. if ( !empty($search) )
  705. $search = " AND ({$search}) ";
  706. $limit_by = ( $limit > 0 ) ? 'LIMIT ' . intval($limit) : '';
  707. } else
  708. return false;
  709. // build the final query
  710. $query = "SELECT t.*, tt.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE 1=1 $search ORDER BY tt.pid ASC $limit_by";
  711. $result = $wpdb->get_results($query);
  712. // TODO: Currently we didn't support a proper pagination
  713. $this->paged['total_objects'] = $this->paged['objects_per_page'] = intval ( $wpdb->get_var( "SELECT FOUND_ROWS()" ) );
  714. $this->paged['max_objects_per_page'] = 1;
  715. // Return the object from the query result
  716. if ($result) {
  717. foreach ($result as $image) {
  718. $images[] = new nggImage( $image );
  719. }
  720. return $images;
  721. }
  722. return null;
  723. }
  724. /**
  725. * search for galleries and return the result
  726. *
  727. * @since 1.7.0
  728. * @param string $request
  729. * @param int $limit number of results, 0 shows all results
  730. * @return Array Result of the request
  731. */
  732. function search_for_galleries( $request, $limit = 0 ) {
  733. global $wpdb;
  734. // If a search pattern is specified, load the posts that match
  735. if ( !empty($request) ) {
  736. // added slashes screw with quote grouping when done early, so done later
  737. $request = stripslashes($request);
  738. // split the words it a array if seperated by a space or comma
  739. preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $request, $matches);
  740. $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
  741. $n = '%';
  742. $searchand = '';
  743. $search = '';
  744. foreach( (array) $search_terms as $term) {
  745. $term = addslashes_gpc($term);
  746. $search .= "{$searchand}((title LIKE '{$n}{$term}{$n}') OR (name LIKE '{$n}{$term}{$n}') )";
  747. $searchand = ' AND ';
  748. }
  749. $term = $wpdb->escape($request);
  750. if (count($search_terms) > 1 && $search_terms[0] != $request )
  751. $search .= " OR (title LIKE '{$n}{$term}{$n}') OR (name LIKE '{$n}{$term}{$n}')";
  752. if ( !empty($search) )
  753. $search = " AND ({$search}) ";
  754. $limit = ( $limit > 0 ) ? 'LIMIT ' . intval($limit) : '';
  755. } else
  756. return false;
  757. // build the final query
  758. $query = "SELECT * FROM $wpdb->nggallery WHERE 1=1 $search ORDER BY title ASC $limit";
  759. $result = $wpdb->get_results($query);
  760. return $result;
  761. }
  762. /**
  763. * search for albums and return the result
  764. *
  765. * @since 1.7.0
  766. * @param string $request
  767. * @param int $limit number of results, 0 shows all results
  768. * @return Array Result of the request
  769. */
  770. function search_for_albums( $request, $limit = 0 ) {
  771. global $wpdb;
  772. // If a search pattern is specified, load the posts that match
  773. if ( !empty($request) ) {
  774. // added slashes screw with quote grouping when done early, so done later
  775. $request = stripslashes($request);
  776. // split the words it a array if seperated by a space or comma
  777. preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $request, $matches);
  778. $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
  779. $n = '%';
  780. $searchand = '';
  781. $search = '';
  782. foreach( (array) $search_terms as $term) {
  783. $term = addslashes_gpc($term);
  784. $search .= "{$searchand}(name LIKE '{$n}{$term}{$n}')";
  785. $searchand = ' AND ';
  786. }
  787. $term = $wpdb->escape($request);
  788. if (count($search_terms) > 1 && $search_terms[0] != $request )
  789. $search .= " OR (name LIKE '{$n}{$term}{$n}')";
  790. if ( !empty($search) )
  791. $search = " AND ({$search}) ";
  792. $limit = ( $limit > 0 ) ? 'LIMIT ' . intval($limit) : '';
  793. } else
  794. return false;
  795. // build the final query
  796. $query = "SELECT * FROM $wpdb->nggalbum WHERE 1=1 $search ORDER BY name ASC $limit";
  797. $result = $wpdb->get_results($query);
  798. return $result;
  799. }
  800. /**
  801. * search for a filename
  802. *
  803. * @since 1.4.0
  804. * @param string $filename
  805. * @param int (optional) $galleryID
  806. * @return Array Result of the request
  807. */
  808. function search_for_file( $filename, $galleryID = false ) {
  809. global $wpdb;
  810. // If a search pattern is specified, load the posts that match
  811. if ( !empty($filename) ) {
  812. // added slashes screw with quote grouping when done early, so done later
  813. $term = $wpdb->escape($filename);
  814. $where_clause = '';
  815. if ( is_numeric($galleryID) ) {
  816. $id = (int) $galleryID;
  817. $where_clause = " AND tt.galleryid = {$id}";
  818. }
  819. }
  820. // build the final query
  821. $query = "SELECT t.*, tt.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE tt.filename = '{$term}' {$where_clause} ORDER BY tt.pid ASC ";
  822. $result = $wpdb->get_row($query);
  823. // Return the object from the query result
  824. if ($result) {
  825. $image = new nggImage( $result );
  826. return $image;
  827. }
  828. return null;
  829. }
  830. /**
  831. * Update or add meta data for an image
  832. *
  833. * @since 1.4.0
  834. * @param int $id The image ID
  835. * @param array $values An array with existing or new values
  836. * @return bool result of query
  837. */
  838. function update_image_meta( $id, $new_values ) {
  839. global $wpdb;
  840. // Query database for existing values
  841. // Use cache object
  842. $old_values = $wpdb->get_var( $wpdb->prepare( "SELECT meta_data FROM $wpdb->nggpictures WHERE pid = %d ", $id ) );
  843. $old_values = unserialize( $old_values );
  844. $meta = array_merge( (array)$old_values, (array)$new_values );
  845. $result = $wpdb->query( $wpdb->prepare("UPDATE $wpdb->nggpictures SET meta_data = %s WHERE pid = %d", serialize($meta), $id) );
  846. wp_cache_delete($id, 'ngg_image');
  847. return $result;
  848. }
  849. /**
  850. * Computes a unique slug for the gallery,album or image, when given the desired slug.
  851. *
  852. * @since 1.7.0
  853. * @author taken from WP Core includes/post.php
  854. * @param string $slug the desired slug (post_name)
  855. * @param string $type ('image', 'album' or 'gallery')
  856. * @param int (optional) $id of the object, so that it's not checked against itself
  857. * @return string unique slug for the object, based on $slug (with a -1, -2, etc. suffix)
  858. */
  859. function get_unique_slug( $slug, $type, $id = 0 ) {
  860. global $wpdb;
  861. switch ($type) {
  862. case 'image':
  863. $check_sql = "SELECT image_slug FROM $wpdb->nggpictures WHERE image_slug = %s AND NOT pid = %d LIMIT 1";
  864. break;
  865. case 'album':
  866. $check_sql = "SELECT slug FROM $wpdb->nggalbum WHERE slug = %s AND NOT id = %d LIMIT 1";
  867. break;
  868. case 'gallery':
  869. $check_sql = "SELECT slug FROM $wpdb->nggallery WHERE slug = %s AND NOT gid = %d LIMIT 1";
  870. break;
  871. default:
  872. return false;
  873. }
  874. //if you didn't give us a name we take the type
  875. $slug = empty($slug) ? $type: $slug;
  876. // Slugs must be unique across all objects.
  877. $slug_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $id ) );
  878. if ( $slug_check ) {
  879. $suffix = 2;
  880. do {
  881. $alt_name = substr ($slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  882. $slug_check = $wpdb->get_var( $wpdb->prepare($check_sql, $alt_name, $id ) );
  883. $suffix++;
  884. } while ( $slug_check );
  885. $slug = $alt_name;
  886. }
  887. return $slug;
  888. }
  889. }
  890. endif;
  891. if ( ! isset($GLOBALS['nggdb']) ) {
  892. /**
  893. * Initate the NextGEN Gallery Database Object, for later cache reasons
  894. * @global object $nggdb Creates a new nggdb object
  895. * @since 1.1.0
  896. */
  897. unset($GLOBALS['nggdb']);
  898. $GLOBALS['nggdb'] = new nggdb() ;
  899. }
  900. ?>