<?php
/**
 * Common parts for photo view
 *
 * This file is part of Zoph.
 *
 * Zoph 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.
 *
 * Zoph 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 Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Zoph
 * @author Jeroen Roos
 */

namespace photo\view;

use conf\conf;
use template\template;
use web\request;
use web\url;

use user;
use photo;
use selection;

/**
 * This is a base view for the photo page, that contains common parts for all views
 * @todo A lot what is here doesn't really belong here, but was moved here when splitting
 *       photo.php in controller and view. Moving them all into their final places would
 *       mean such an enormous amount of changes that bugs would be guaranteed.
 *       Once the dust has settled, I can revisit this and make more changes.
 */
abstract class common {

    /** * @var array request variables */
    protected $vars;
    /** * @var request web request */
    protected $request;
    /** * @var photo */
    protected $photo;

    /** @var int total number of photos return by the query */
    public $photocount = 0;
    /** @var int offset in the query for the current photo */
    public $offset = 0;

    /** @var string Contains url of next image */
    protected $nextURL = "";
    /** @var string Contains url of prev image */
    protected $prevURL = "";
    /** @var string Contains url for 'up' link  */
    protected $upURL = "";

    /**
     * Create view
     * @param request web request
     * @param photo the photo that this page is dealing with
     */
    public function __construct(request $request, photo $photo) {
        $this->request=$request;
        $this->vars=$request->getRequestVars();
        $this->photo=$photo;
    }

    /**
     * Get permissions for the current photo
     * @todo refactor out
     */
    protected function getPermissions() {
        $user=user::getCurrent();
        if (!$user->isAdmin()) {
            return $user->getPhotoPermissions($this->photo);
        }
    }

    /**
     * Create "next" "previous" and "up" links for the photo page
     */
    public function setLinks() {
        $act = "";

        if (isset($this->request["_off"])) {
            $user=user::getCurrent();
            $ignore=array("_off", "_action");

            $cols = (int) $this->request["_cols"];
            $rows = (int) $this->request["_rows"];
            $offset  = (int) $this->request["_off"];
            $_action  = $this->request["_action"];

            $cols = $cols ? $cols : $user->prefs->get("num_cols");
            $rows = $rows ? $rows : $user->prefs->get("num_rows");

            $cells = $cols * $rows;

            $upQs = http_build_query($this->request->getUpdatedVars(null, null, $ignore));

            if ($cells) {
                $off = $cells * floor($offset / ($cells));
                $upQs .= "&amp;_off=" . $off;
            }
            $this->upURL="photos.php?" . $upQs;

            if (isset($_action) && !empty($_action="")) {
                $act="_action=" . $_action . "&";
            }
            if ($offset > 0) {
                $newoffset = $offset - 1;
                $this->prevURL=$this->request->getServerVar("PHP_SELF") . "?" . $act .
                    htmlentities(
                        str_replace("_off=$offset", "_off=$newoffset", $this->request->getReturnQueryString())
                    );
            }
            if ($offset + 1 < $this->photocount) {
                $newoffset = $offset + 1;
                $this->nextURL = $this->request->getServerVar("PHP_SELF") . "?" . $act .
                    htmlentities(
                        str_replace("_off=$offset", "_off=$newoffset", $this->request->getReturnQueryString())
                    );
            }

        }
    }


    /**
     * Get selection block for current photo
     * @return block template block
     */
    protected function getSelection() {
        try {
            $selection=new selection($_SESSION, array(
                "relate"        => "relation.php?_action=new&amp;photo_id_1=" . $this->photo->getId() .
                                   "&amp;photo_id_2=",
                "return"        => "_return=photo.php&amp;_qs=" . $this->request->getEncodedQueryString()
            ), $this->photo);
        } catch (\photoNoSelectionException $e) {
            $selection=null;
        }
        return $selection;
    }

    /**
     * Get 'share' block for current photo
     * @return block template block
     */
    protected function getShare() {
        if (conf::get("share.enable") && (user::getCurrent()->isAdmin() || user::getCurrent()->get("allow_share"))) {
            $hash=$this->photo->getHash();
            $fullHash=sha1(conf::get("share.salt.full") . $hash);
            $midHash=sha1(conf::get("share.salt.mid") . $hash);
            $fullLink=url::get() . "image.php?hash=" . $fullHash;
            $midLink=url::get() . "image.php?hash=" . $midHash;

            $share=new template("photo_share", array(
                "hash" => $hash,
                "full_link" => $fullLink,
                "mid_link" => $midLink
            ));
        }
        return isset($share) ? $share : null;
    }


    /**
     * Get the title for the current photo
     * @param int number of photos
     * @param int offset from first photo
     * @return block template block
     */
    protected function getTitle($photoCount, $offset) {
        if ($photoCount) {
            return sprintf(translate("photo %s of %s"), ($offset + 1), $photoCount);
        } else if ($this->photo instanceof photo) {
            return $this->photo->get("name");
        } else {
            return translate("photo");
        }
    }

    /**
     * Create the actionlinks for this page
     */
    protected function getActionlinks() {
        $user=user::getCurrent();
        $regexAction=array("/_action=\w+&?/");
        $actionlinks=array();

        if (conf::get("feature.mail")) {
            $actionlinks["email"]="mail.php?_action=compose&amp;photo_id=" . $this->photo->getId();
        }

        if ($user->isAdmin() || $this->getPermissions()->get("writable")) {
            $actionlinks["edit"]="photo.php?_action=edit&" . $this->request->getReturnQueryString();
        }
        if ($user->isAdmin() || ($user->canDeletePhotos() && $this->getPermissions()->get("writable"))) {
            $actionlinks["delete"]="photo.php?_action=delete&amp;photo_id=" . $this->photo->getId() .
                "&amp;_qs=" . $this->request->getEncodedQueryString();
        }
        if ($user->get("lightbox_id")) {
            $actionlinks["lightbox"]="photo.php?_action=lightbox&amp;" . $this->request->getQueryString();
        }
        if (conf::get("feature.comments") && (user::getCurrent()->canLeaveComments())) {
            $actionlinks["add comment"]="comment.php?_action=new&amp;photo_id=" . $this->photo->getId();
        }
        if ($user->isAdmin()) {
            $actionlinks["select"]="photo.php?_action=select&amp;" . $this->request->getReturnQueryString();
        }
        return $actionlinks;
    }

    /**
     * Output view
     */
    abstract public function view();
}
