/**
  * Get album images.
  */
 public function albumImages($nid, $limit = 10) {
   $images = array();
   $column = isset($_GET['field']) ? \Drupal\Component\Utility\Html::escape($_GET['field']) : '';
   $sort = isset($_GET['sort']) ? \Drupal\Component\Utility\Html::escape($_GET['sort']) : '';
   $term = _photos_order_value($column, $sort, $limit, array('column' => 'p.wid', 'sort' => 'asc'));
   $query = db_select('file_managed', 'f')
     ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
   $query->join('photos_image', 'p', 'p.fid = f.fid');
   $query->join('users_field_data', 'u', 'f.uid = u.uid');
   $query->join('node_field_data', 'n', 'n.nid = p.pid');
   $query->fields('f', array('uri', 'filemime', 'created', 'filename', 'filesize'));
   $query->fields('p');
   $query->fields('u', array('uid', 'name'));
   $query->condition('p.pid', $nid);
   $query->limit($term['limit']);
   $query->orderBy($term['order']['column'], $term['order']['sort']);
   $query->addTag('node_access');
   $result = $query->execute();
   foreach ($result as $data) {
     $images[] = photos_get_info(0, $data);
   }
   if (isset($images[0]->fid)) {
     $node = \Drupal::entityManager()->getStorage('node')->load($nid);
     $images[0]->info = array(
       'pid' => $node->id(),
       'title' => $node->getTitle(),
       'uid' => $node->uid
     );
     if (isset($node->album['cover'])) {
       $images[0]->info['cover'] = $node->album['cover'];
     }
   }
   return $images;
 }
  /**
   * Album views.
   */
  public function albumViews($type, $limit, $url = 0, $uid = 0, $sort = ' n.nid DESC') {
    $query = db_select('photos_album', 'p');
    $query->join('node_field_data', 'n', 'n.nid = p.pid');
    $query->join('users_field_data', 'u', 'u.uid = n.uid');
    $query->fields('p', array('count', 'fid'))
      ->fields('n', array('nid', 'title'))
      ->fields('u', array('uid', 'name'));
    $query->condition('n.status', 1);

    if ($type == 'user') {
      $query->condition('n.uid', $uid);
    }
    if ($type == 'rand') {
      $query->orderRandom();
    }
    else {
      $query->orderBy('n.nid', 'DESC');
    }
    $query->range(0, $limit);
    $query->addTag('node_access');
    $results = $query->execute();

    $i = 0;
    foreach ($results as $result) {
      if ($result->fid) {
        $render_view = photos_get_info($result->fid, 0, array('href' => 'photos/album/' . $result->nid, 'filename' => $result->title));
        $view = drupal_render($render_view);
      }
      else {
        $query = db_select('file_managed', 'f');
        $query->join('photos_image', 'p', 'p.fid = f.fid');
        $query->fields('f', array('fid', 'uri', 'filename'));
        $query->condition('p.pid', $result->nid);
        $query->orderBy('f.fid', 'DESC');
        $image = $query->execute()->fetchObject();
        if (isset($image->fid)) {
          $render_view = photos_get_info($image->fid, $image, array('href' => 'photos/album/' . $result->nid, 'filename' => $result->title));
          $view = drupal_render($render_view);
        }
        else {
          $view = '';
        }
      }
      $album[] = array('node' => $result, 'view' => $view);
      ++$i;
    }
    if ($i) {
      $photo_block = array(
        '#theme' => 'photos_block',
        '#images' => $album,
        '#block_type' => 'album'
      );
      $content = drupal_render($photo_block);
      $url = Url::fromUri('base:' . $url);
      if ($url && $i >= $limit) {
        $more_link = array(
          '#type' => 'more_link',
          '#url' => $url,
          '#title' => t('View more')
        );
        $content .= drupal_render($more_link);
      }
      if ($type == 'user') {
        return array(
          'content' => $content,
          'title' => $album[0]['node']->name . "'s Albums"
        );
      }
      else {
        return $content;
      }
    }
  }
  /**
   * Photos image view pager block.
   */
  public static function imagePager($fid, $id, $type = 'pid') {
    $query = db_select('file_managed', 'f');
    $query->join('photos_image', 'p', 'f.fid = p.fid');
    $query->fields('p', array('pid'))
      ->fields('f', array('fid', 'uri', 'filename'));

    // Default order by fid.
    $order = array('column' => 'f.fid', 'sort' => 'DESC');
    if ($type == 'pid') {
      // Viewing album.
      // Order images by album settings.
      $album_data = db_query('SELECT data FROM {photos_album} WHERE pid = :pid', array(':pid' => $id))->fetchField();
      $album_data = unserialize($album_data);
      $default_order = \Drupal::config('photos.settings')->get('photos_display_imageorder');
      $image_order = isset($album_data['imageorder']) ? $album_data['imageorder'] : $default_order;
      $order = explode('|', $image_order);
      $order = _photos_order_value_change($order[0], $order[1]);
      $query->condition('p.pid', $id);
    }
    elseif ($type == 'uid') {
      // Viewing all user images.
      $query->condition('f.uid', $id);
    }
    elseif ($type == 'sub') {
      // Viewing sub-album.
      // Default order by wid.
      $order = array('column' => 's.wid', 'sort' => 'ASC');
      $query->join('photos_node', 's', 's.fid = p.fid');
      $query->condition('s.nid', $id);
    }
    else {
      // Show all.
    }
    $query->orderBy($order['column'], $order['sort']);
    $result = $query->execute();

    $stop = $t['prev'] = $t['next'] = 0;
    $num = 0;
    foreach ($result as $image) {
      $num++;
      if ($stop == 1) {
        $t['next'] = $image;
        $t['next_view'] = photos_get_info(0, $t['next'], array('style_name' => \Drupal::config('photos.settings')->get('photos_pager_imagesize')));
        if ($type == 'sub') {
          // Sub-album next image.
          $url = Url::fromUri('base:photos/image/' . $image->fid);
          $t['next_url'] = url($url, array('query' => array('photos_sub' => $id)));
        }
        else {
          // Next image.
          $t['next_url'] = Url::fromUri('base:photos/image/' . $image->fid)->toString();
        }
        break;
      }
      if ($image->fid == $fid) {
        $t['current'] = $image;
        $t['current_view'] = photos_get_info(0, $t['current'], array('style_name' => \Drupal::config('photos.settings')->get('photos_pager_imagesize')));
        $stop = 1;
      }
      else {
        $t['prev'] = $image;
      }
    }
    if ($t['prev']) {
      $t['prev_view'] = photos_get_info(0, $t['prev'], array('style_name' => \Drupal::config('photos.settings')->get('photos_pager_imagesize')));
      if ($type == 'sub') {
        // Sub-album previous image.
        $url = Url::fromUri('base:photos/image/' . $t['prev']->fid);
        $t['prev_url'] = url($url, array('query' => array('photos_sub' => $id)));
      }
      else {
        // Previous image.
        $t['prev_url'] = Url::fromUri('base:photos/image/' . $t['prev']->fid)->toString();
      }
    }

    return $t;
  }
  /**
   * Sub album page view.
   */
  public function subAlbumView($node) {
    if (!is_object($node)) {
      // Load node object.
      $node = \Drupal\node\Entity\Node::load($nid);
    }
    $order = explode('|', \Drupal::config('photos.settings')->get('photos_display_imageorder'));
    $order = _photos_order_value_change($order[0], $order[1]);
    $column = isset($_GET['field']) ? \Drupal\Component\Utility\Html::escape($_GET['field']) : '';
    $sort = isset($_GET['sort']) ? \Drupal\Component\Utility\Html::escape($_GET['sort']) : '';
    $term = _photos_order_value($column, $sort, \Drupal::config('photos.settings')->get('photos_display_viewpager'), $order);
    // Override weight sort for sub albums.
    if ($term['order']['column'] == 'p.wid') $term['order']['column'] = 'a.wid';
    $query = db_select('file_managed', 'f')->extend('Drupal\Core\Database\Query\PagerSelectExtender');
    $query->join('photos_image', 'p', 'p.fid = f.fid');
    $query->join('photos_node', 'a', 'a.fid = f.fid');
    $query->join('node', 'n', 'n.nid = p.pid');
    $query->join('users_field_data', 'u', 'u.uid = f.uid');
    $query->addField('n', 'title', 'album_title');
    $query->fields('f', array('uri', 'filemime', 'created', 'filename', 'filesize'))
      ->fields('p')
      ->fields('a')
      ->fields('u', array('uid', 'name'))
      ->condition('a.nid', $node->id());
    $query->orderBy($term['order']['column'], $term['order']['sort']);
    $query->range(0, $term['limit']);
    $result = $query->execute();

    $com = \Drupal::config('photos.settings')->get('photos_comment');
    $edit = $node->access('update');
    $del = $node->access('delete');
    $vote = \Drupal::config('photos.settings')->get('photos_vote');
    $style_name = \Drupal::config('photos.settings')->get('photos_display_list_imagesize');
    foreach ($result as $data) {
      $image = photos_get_info(0, $data);
      $image->view = array(
        '#theme' => 'photos_image_html',
        '#style_name' => $style_name,
        '#image' => $image
      );

      $image->url = Url::fromUri('base:photos/image/' . $image->fid, array('query' => array('photos_sub' => $image->nid)))->toString();

      if ($com) {
        $image->links['comment'] = array(
          '#theme' => 'photos_comment_count',
          '#comcount' => $image->comcount,
          '#url' => $image->url
        );
      }
      if ($image->count) {
        $image->links['count'] = \Drupal::translation()->formatPlural($image->count, '!cou visit', '!cou visits', array('!cou' => $image->count));
      }
      $image->links['info'] = t('Uploaded by @name on @time to @title', array(
        '@name' => $image->name,
        '@time' => \Drupal::service('date.formatter')->format($image->created, 'short'),
        '@title' => \Drupal::l($image->album_title, Url::fromUri('base:photos/album/' . $image->pid))
      ));

      $image->class = array(
        'title_class' => '',
        'des_class' => '',
      );
      $image->id = array(
        'des_edit' => '',
        'title_edit' => ''
      );
      if ($edit) {
        $image->ajax['edit_url'] = $image->url . '/update';
        // $image->links['cover'] = l(t('Set as Cover'), 'node/' . $image->pid . '/photos/cover/' . $image->fid, array('query' => drupal_get_destination()));
        $image->class = array(
          'title_class' => ' jQueryeditable_edit_title',
          'des_class' => ' jQueryeditable_edit_des',
        );
        $image->id = array(
          'des_edit' => ' id="photos-image-edit-des-' . $image->fid . '"',
          'title_edit' => ' id="photos-image-edit-title-' . $image->fid . '"'
        );
      }
      $image->ajax['del_id'] = '';
      if ($del) {
        $image->ajax['del_id'] = 'id="photos_ajax_del_' . $image->fid . '"';
        $current_path = \Drupal::service('path.current')->getPath();
        $image->ajax['del_link'] = \Drupal::l(t('Move out'), Url::fromUri('base:photos/image/' . $image->fid . '/delete', array(
          'query' => array(
            'destination' => $current_path,
            'type' => 'sub_album',
            'nid' => $node->id()
          ),
          'attributes' => array(
            'class' => 'colorbox-load',
          )
        )));
      }
      if ($vote) {
        $image->links['vote'] = array(
          '#theme' => 'photos_vote',
          '#fid' => $image->fid
        );
      }
      $album['view'][] = array(
        '#theme' => 'photos_image_view',
        '#image' => $image,
        '#display_type' => 'list'
      );
    }
    if (isset($album['view'][0])) {
      $album['node_url'] = Url::fromUri('base:node/' . $node->id())->toString();
      $album['album_url'] = Url::fromUri('base:photos/sub_album/' . $node->id())->toString();
      $album['links'] = _photos_order_link('photos/album/' . $node->id(), $node->subalbum['count'], 0, 1);
      $album['pager'] = array('#type' => 'pager');

      if (isset($node->album['cover']['url'])) {
        $style_name = \Drupal::config('photos.settings')->get('photos_cover_imagesize') ?: 'thumbnail';
        $album_cover = array(
          '#theme' => 'image_style',
          '#style_name' => $style_name,
          '#path' => $node->album['cover']['url'],
          '#alt' => $node->getTitle(),
          '#title' => $node->getTitle()
        );
        $album['cover'] = $album_cover;
      }
      $content = array(
        '#theme' => 'photos_album_view',
        '#album' => $album,
        '#node' => $node
      );
    }
    else {
      $content = t('Sub-Album is empty');
    }

    return $content;
  }
  /**
   * Returns content for recent images.
   *
   * @return string
   *   A HTML-formatted string with the administrative page content.
   *
   */
  public function contentOverview() {
    $user = \Drupal::currentUser();
    $build = array();
    $order = explode('|', \Drupal::config('photos.settings')->get('photos_display_imageorder'));
    $order = _photos_order_value_change($order[0], $order[1]);
    $column = (isset($_GET['field'])) ? \Drupal\Component\Utility\Html::escape($_GET['field']) : 0;
    $sort = (isset($_GET['sort'])) ? \Drupal\Component\Utility\Html::escape($_GET['sort']) : 0;
    // @todo recent images default sort should be created desc.
    $term = _photos_order_value($column, $sort, \Drupal::config('photos.settings')->get('photos_display_viewpager'), $order);
    $query = db_select('file_managed', 'f')
      ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
    $query->join('photos_image', 'p', 'p.fid = f.fid');
    $query->join('node_field_data', 'n', 'n.nid = p.pid');
    $query->join('users_field_data', 'u', 'u.uid = f.uid');
    $query->fields('f', array('uri', 'filemime', 'created', 'filename', 'filesize'))
      ->fields('p')
      ->fields('u', array('uid', 'name'));
    $query->addField('n', 'title', 'node_title');
    $query->orderBy($term['order']['column'], $term['order']['sort']);
    $query->limit($term['limit']);
    $query->addTag('node_access');
    $results = $query->execute();

    $album['links'] = _photos_order_link('photos/image', photos_get_count('site_image'), 0, 1);
    $com = \Drupal::config('photos.settings')->get('photos_comment');
    $edit = 0;

    // @todo fix voting?
    $vote = FALSE;
    // $vote = variable_get('allowed to vote', 0);

    $style_name = \Drupal::config('photos.settings')->get('photos_display_list_imagesize');
    foreach ($results as $data) {
      $image = photos_get_info(0, $data);
      $image->title = \Drupal\Component\Utility\SafeMarkup::checkPlain($image->title);
      $image->des = \Drupal\Component\Utility\SafeMarkup::checkPlain($image->des);
      $image->view = array(
        '#theme' => 'photos_image_html',
        '#style_name' => $style_name,
        '#image' => $image
      );

      $image->url = Url::fromUri('base:photos/image/' . $image->fid)->toString();

      if ($com) {
        $image->links['comment'] = array(
          '#theme' => 'photos_comment_count',
          '#comcount' => $image->comcount,
          '#url' => $image->url
        );
      }
      if (isset($image->count)) {
        $image->links['count'] = \Drupal::translation()->formatPlural($image->count, '@cou visit', '@cou visits', array('@cou' => $image->count));
      }
      // Get username.
      $name = '';
      if (!empty($image->uid)) {
        $account = \Drupal::entityManager()->getStorage('user')->load($image->uid);
        $name_render_array = array(
          '#theme' => 'username',
          '#account' => $account
        );
        $name = drupal_render($name_render_array);
      }
      $image->links['info'] = t('Uploaded on @time by @name in @title', array(
        '@name' => $name,
        '@time' => \Drupal::service('date.formatter')->format($image->created, 'short'),
        '@title' => \Drupal::l($image->node_title, Url::fromUri('base:photos/album/' . $image->pid))
      ));
      $image->class = array(
        'title_class' => '',
        'des_class' => '',
      );
      $image->id = array(
        'des_edit' => '',
        'title_edit' => ''
      );
      $image->ajax['del_id'] = '';
      if ($edit) {
        $image->ajax['edit_url'] = $image->url . '/update';
        $current_path = \Drupal::service('path.current')->getPath();
        $image->ajax['edit_link'] = \Drupal::l(t('Edit'), Url::fromUri('base:photos/image/' . $image->fid . '/edit'), array(
          'query' => array(
            'destination' => $current_path,
            'pid' => $image->pid,
            'uid' => $image->uid
          ),
          'attributes' => array(
            'class' => array('colorbox-load', 'photos-edit-edit')
          )
        ));

        $image->class = array(
          'title_class' => ' jQueryeditable_edit_title',
          'des_class' => ' jQueryeditable_edit_des',
        );
        $image->id = array(
          'des_edit' => ' id="photos-image-edit-des-' . $image->fid . '"',
          'title_edit' => ' id="photos-image-edit-title-' . $image->fid . '"'
        );
        $image->ajax['del_id'] = 'id="photos_ajax_del_' . $image->fid . '"';
        $image->ajax['del_link'] = \Drupal::l(t('Delete'), Url::fromUri('base:photos/image/' . $image->fid . '/delete'), array(
          'query' => array(
            'destination' => $current_path,
            'pid' => $image->pid,
            'uid' => $image->uid
          ),
          'attributes' => array(
            'class' => array('photos-edit-delete'),
            'alt' => 'photos_ajax_del_' . $image->fid
          )
        ));

        // Set cover link.
        $url_query = drupal_get_destination();
        $cover_url = Url::fromRoute('photos.album.update.cover', array(
          'node' => $image->pid,
          'file' => $image->fid
        ),
        array(
          'query' => $url_query
        ));
        $image->links['cover'] = \Drupal::l(t('Set to Cover'), $cover_url);
      }
      if ($vote) {
        $image->links['vote'] = array(
          '#theme' => 'photos_vote',
          '#fid' => $image->fid
        );
      }
      $album['view'][] = array(
        '#theme' => 'photos_image_view',
        '#image' => $image,
        '#display_type' => 'list'
      );
    }
    if (isset($album['view'][0])) {
      // Set pager.
      $album['pager'] = array(
        '#type' => 'pager'
      );
      $render_album_view = array(
        '#theme' => 'photos_album_view',
        '#album' => $album,
        '#node' => NULL
      );
      $content = drupal_render($render_album_view);
    }
    else {
      if ($account <> FALSE) {
        $content = t('@name has not uploaded any images yet.', array('@name' => $account->name));
      }
      else {
        $content = t('No images have been uploaded yet.');
      }
    }

    return array(
      '#markup' => $content
    );
  }