public function edit($id, $step = 'userProfile') { $project = Model\Project::get($id, null); // para que tenga todas las imágenes $project->gallery = Model\Image::getAll($id, 'project'); // aunque pueda acceder edit, no lo puede editar si if ($project->owner != $_SESSION['user']->id && (isset($_SESSION['admin_node']) && $_SESSION['admin_node'] != \GOTEO_NODE) && (isset($_SESSION['admin_node']) && $project->node != $_SESSION['admin_node']) && !isset($_SESSION['user']->roles['superadmin']) && (isset($_SESSION['user']->roles['checker']) && !Model\User\Review::is_assigned($_SESSION['user']->id, $project->id))) { Message::Info('No tienes permiso para editar este proyecto'); throw new Redirection('/admin/projects'); } // si no tenemos SESSION stepped es porque no venimos del create if (!isset($_SESSION['stepped'])) { $_SESSION['stepped'] = array('userProfile' => 'userProfile', 'userPersonal' => 'userPersonal', 'overview' => 'overview', 'costs' => 'costs', 'rewards' => 'rewards', 'supports' => 'supports'); } if ($project->status != 1 && !ACL::check('/project/edit/todos')) { // solo puede estar en preview $step = 'preview'; $steps = array('preview' => array('name' => Text::get('step-7'), 'title' => Text::get('step-preview'), 'offtopic' => true)); } else { // todos los pasos // entrando, por defecto, en el paso especificado en url $steps = array('userProfile' => array('name' => Text::get('step-1'), 'title' => Text::get('step-userProfile'), 'offtopic' => true), 'userPersonal' => array('name' => Text::get('step-2'), 'title' => Text::get('step-userPersonal'), 'offtopic' => true), 'overview' => array('name' => Text::get('step-3'), 'title' => Text::get('step-overview')), 'costs' => array('name' => Text::get('step-4'), 'title' => Text::get('step-costs')), 'rewards' => array('name' => Text::get('step-5'), 'title' => Text::get('step-rewards')), 'supports' => array('name' => Text::get('step-6'), 'title' => Text::get('step-supports')), 'preview' => array('name' => Text::get('step-7'), 'title' => Text::get('step-preview'), 'offtopic' => true)); } foreach ($_REQUEST as $k => $v) { if (strncmp($k, 'view-step-', 10) === 0 && !empty($v) && !empty($steps[substr($k, 10)])) { $step = substr($k, 10); } } if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST)) { $errors = array(); // errores al procesar, no son errores en los datos del proyecto foreach ($steps as $id => &$data) { if (call_user_func_array(array($this, "process_{$id}"), array(&$project, &$errors))) { // si un process devuelve true es que han enviado datos de este paso, lo añadimos a los pasados if (!in_array($id, $_SESSION['stepped'])) { $_SESSION['stepped'][$id] = $id; } } } // guardamos los datos que hemos tratado y los errores de los datos $project->save($errors); // hay que mostrar errores en la imagen if (!empty($errors['image'])) { $project->errors['overview']['image'] = $errors['image']; $project->okeys['overview']['image'] = null; } // si estan enviando el proyecto a revisión if (isset($_POST['process_preview']) && isset($_POST['finish'])) { $errors = array(); $old_id = $project->id; if ($project->ready($errors)) { if ($_SESSION['project']->id == $old_id) { $_SESSION['project'] = $project; } // email a los de goteo $mailHandler = new Mail(); $mailHandler->reply = $project->user->email; $mailHandler->replyName = "{$project->user->name}"; $mailHandler->to = \GOTEO_MAIL; $mailHandler->toName = 'Revisor de proyectos'; $mailHandler->subject = 'Proyecto ' . $project->name . ' enviado a valoración'; $mailHandler->content = '<p>Han enviado un nuevo proyecto a revisión</p><p>El nombre del proyecto es: <span class="message-highlight-blue">' . $project->name . '</span> <br />y se puede ver en <span class="message-highlight-blue"><a href="' . SITE_URL . '/project/' . $project->id . '">' . SITE_URL . '/project/' . $project->id . '</a></span></p>'; $mailHandler->html = true; $mailHandler->template = 0; if ($mailHandler->send($errors)) { Message::Info(Text::get('project-review-request_mail-success')); } else { Message::Error(Text::get('project-review-request_mail-fail')); Message::Error(implode('<br />', $errors)); } unset($mailHandler); // email al autor // Obtenemos la plantilla para asunto y contenido $template = Template::get(8); // Sustituimos los datos $subject = str_replace('%PROJECTNAME%', $project->name, $template->title); // En el contenido: $search = array('%USERNAME%', '%PROJECTNAME%'); $replace = array($project->user->name, $project->name); $content = \str_replace($search, $replace, $template->text); $mailHandler = new Mail(); $mailHandler->to = $project->user->email; $mailHandler->toName = $project->user->name; $mailHandler->subject = $subject; $mailHandler->content = $content; $mailHandler->html = true; $mailHandler->template = $template->id; if ($mailHandler->send($errors)) { Message::Info(Text::get('project-review-confirm_mail-success')); } else { Message::Error(Text::get('project-review-confirm_mail-fail')); Message::Error(implode('<br />', $errors)); } unset($mailHandler); // Evento Feed $log = new Feed(); $log->setTarget($project->id); $log->populate('El proyecto ' . $project->name . ' se ha enviado a revision', '/project/' . $project->id, \vsprintf('%s ha inscrito el proyecto %s para <span class="red">revisión</span>, el estado global de la información es del %s', array(Feed::item('user', $project->user->name, $project->user->id), Feed::item('project', $project->name, $project->id), Feed::item('relevant', $project->progress . '%')))); $log->doAdmin('project'); unset($log); throw new Redirection("/dashboard?ok"); } } } elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST)) { throw new Error(Error::INTERNAL, 'FORM CAPACITY OVERFLOW'); } //re-evaluar el proyecto $project->check(); // variables para la vista $viewData = array('project' => $project, 'steps' => $steps, 'step' => $step); // segun el paso añadimos los datos auxiliares para pintar switch ($step) { case 'userProfile': $owner = Model\User::get($project->owner, null); // si es el avatar por defecto no lo mostramos aqui if ($owner->avatar->id == 1) { unset($owner->avatar); } $viewData['user'] = $owner; $viewData['interests'] = Model\User\Interest::getAll(); if ($_POST) { foreach ($_POST as $k => $v) { if (!empty($v) && preg_match('/web-(\\d+)-edit/', $k, $r)) { $viewData[$k] = true; } } if (!empty($_POST['web-add'])) { $last = end($owner->webs); if ($last !== false) { $viewData["web-{$last->id}-edit"] = true; } } } break; case 'userPersonal': $viewData['account'] = Model\Project\Account::get($project->id); break; case 'overview': $viewData['categories'] = Model\Project\Category::getAll(); // $viewData['currently'] = Model\Project::currentStatus(); // $viewData['scope'] = Model\Project::scope(); break; case 'costs': $viewData['types'] = Model\Project\Cost::types(); if ($_POST) { foreach ($_POST as $k => $v) { if (!empty($v) && preg_match('/cost-(\\d+)-edit/', $k, $r)) { $viewData[$k] = true; } } if (!empty($_POST['cost-add'])) { $last = end($project->costs); if ($last !== false) { $viewData["cost-{$last->id}-edit"] = true; } } } break; case 'rewards': $viewData['stypes'] = Model\Project\Reward::icons('social'); $viewData['itypes'] = Model\Project\Reward::icons('individual'); $viewData['licenses'] = Model\Project\Reward::licenses(); // $viewData['types'] = Model\Project\Support::types(); if ($_POST) { foreach ($_POST as $k => $v) { if (!empty($v) && preg_match('/((social)|(individual))_reward-(\\d+)-edit/', $k)) { $viewData[$k] = true; } } if (!empty($_POST['social_reward-add'])) { $last = end($project->social_rewards); if ($last !== false) { $viewData["social_reward-{$last->id}-edit"] = true; } } if (!empty($_POST['individual_reward-add'])) { $last = end($project->individual_rewards); if ($last !== false) { $viewData["individual_reward-{$last->id}-edit"] = true; } } } break; case 'supports': $viewData['types'] = Model\Project\Support::types(); if ($_POST) { foreach ($_POST as $k => $v) { if (!empty($v) && preg_match('/support-(\\d+)-edit/', $k, $r)) { $viewData[$k] = true; } } if (!empty($_POST['support-add'])) { $last = end($project->supports); if ($last !== false) { $viewData["support-{$last->id}-edit"] = true; } } } break; case 'preview': $success = array(); if (empty($project->errors)) { $success[] = Text::get('guide-project-success-noerrors'); } if ($project->finishable) { $success[] = Text::get('guide-project-success-minprogress'); $success[] = Text::get('guide-project-success-okfinish'); } $viewData['success'] = $success; $viewData['types'] = Model\Project\Cost::types(); break; } $view = new View("view/project/edit.html.php", $viewData); return $view; }
private function view($id, $show, $post = null) { $project = Model\Project::get($id, LANG); // recompensas foreach ($project->individual_rewards as &$reward) { $reward->none = false; $reward->taken = $reward->getTaken(); // cofinanciadores quehan optado por esta recompensas // si controla unidades de esta recompensa, mirar si quedan if ($reward->units > 0 && $reward->taken >= $reward->units) { $reward->none = true; } } // mensaje cuando, sin estar en campaña, tiene fecha de publicación, es que la campaña ha sido cancelada if ($project->status < 3 && !empty($project->published)) { Message::Info(Text::get('project-unpublished')); } elseif ($project->status < 3) { // mensaje de no publicado siempre que no esté en campaña Message::Info(Text::get('project-not_published')); } // solamente se puede ver publicamente si... $grant = false; if ($project->status > 2) { // está publicado $grant = true; } elseif ($project->owner == $_SESSION['user']->id) { // es el dueño $grant = true; } elseif (ACL::check('/project/edit/todos')) { // es un admin $grant = true; } elseif (ACL::check('/project/view/todos')) { // es un usuario con permiso $grant = true; } elseif (isset($_SESSION['user']->roles['checker']) && Model\User\Review::is_assigned($_SESSION['user']->id, $project->id)) { // es un revisor y lo tiene asignado $grant = true; } // (Callsys) // si lo puede ver if ($grant) { $viewData = array('project' => $project, 'show' => $show); // sus entradas de novedades $blog = Model\Blog::get($project->id); // si está en modo preview, ponemos todas las entradas, incluso las no publicadas if (isset($_GET['preview']) && $_GET['preview'] == $_SESSION['user']->id) { $blog->posts = Model\Blog\Post::getAll($blog->id, null, false); } $viewData['blog'] = $blog; // tenemos que tocar esto un poquito para motrar las necesitades no economicas if ($show == 'needs-non') { $viewData['show'] = 'needs'; $viewData['non-economic'] = true; } if ($show == 'messages' && is_numeric($_GET['msgto'])) { $support = Model\Project\Support::get($_GET['msgto']); if (is_numeric($support->thread)) { $viewData['thread'] = $support->thread; } } // -- Mensaje azul molesto para usuarios no registrados if (($show == 'messages' || $show == 'updates' || $show == 'evaluation') && empty($_SESSION['user'])) { Message::Info(Text::html('user-login-required')); } //tenemos que tocar esto un poquito para gestionar los pasos al aportar if ($show == 'invest') { // si no está en campaña no pueden estar aqui ni de coña if ($project->status != 3) { Message::Info(Text::get('project-invest-closed')); throw new Redirection('/project/' . $id, Redirection::TEMPORARY); } $viewData['show'] = 'supporters'; /* pasos de proceso aporte * * 1, 'start': ver y seleccionar recompensa (y cantidad) * 2, 'login': loguear con usuario/contraseña o con email (que crea el usuario automáticamente) * 3, 'confirm': confirmar los datos y saltar a la pasarela de pago * 4, 'ok'/'fail': al volver de la pasarela de pago, la confirmación nos dice si todo bien o algo mal * 5, 'continue': recuperar aporte incompleto (variante de confirm) */ // usamos la variable de url $post para movernos entre los pasos $step = isset($post) && in_array($post, array('start', 'login', 'confirm', 'continue')) ? $post : 'start'; // si llega confirm ya ha terminado el proceso de aporte if (isset($_GET['confirm']) && \in_array($_GET['confirm'], array('ok', 'fail'))) { unset($_SESSION['invest-amount']); // confirmación $step = $_GET['confirm']; } else { // si no, a ver en que paso estamos if (isset($_GET['amount'])) { $_SESSION['invest-amount'] = $_GET['amount']; } // si el usuario está validado, recuperamos posible amount y mostramos if ($_SESSION['user'] instanceof Model\User) { $step = 'confirm'; } elseif ($step != 'start' && empty($_SESSION['user'])) { // si no está validado solo puede estar en start Message::Info(Text::get('user-login-required-to_invest')); $step = 'start'; } elseif ($step == 'start') { // para cuando salte $_SESSION['jumpto'] = SEC_URL . '/project/' . $id . '/invest/#continue'; } else { $step = 'start'; } } $viewData['step'] = $step; } if ($show == 'updates') { $viewData['post'] = $post; $viewData['owner'] = $project->owner; } if ($show == 'messages' && $project->status < 3) { Message::Info(Text::get('project-messages-closed')); } return new View(VIEW_PATH . '/project/view.html.php', $viewData); } else { // no lo puede ver throw new Redirection("/"); } }
<div id="main" class="threecols"> <div class="center <?php echo $show; ?>"> <?php $non_flug = 0; // los modulos centrales son diferentes segun el show switch ($show) { case 'needs': echo new View('view/m/project/widget/summary.h_ttl.html.php', array('project' => $project)); if ($this['non-economic']) { echo new View('view/m/project/widget/non-needs.html.php', array('project' => $project, 'types' => Support::types())); $non_flug = 1; } else { echo new View('view/m/project/widget/needs.html.php', array('project' => $project, 'types' => Cost::types())), new View('view/m/project/widget/schedule.html.php', array('project' => $project)), new View('view/m/project/widget/sendMsg.html.php', array('project' => $project)); } break; case 'supporters': echo new View('view/m/project/widget/summary.h_ttl.html.php', array('project' => $project)); // segun el paso de aporte if (!empty($step) && in_array($step, array('start', 'login', 'confirm', 'continue', 'ok', 'fail'))) {
/** * Graba las colaboraciones con lo recibido por POST * * @param object $project Instancia de proyecto de trabajo * @param array $errors (por referncia) * @return object $project Instancia de proyecto modificada */ public static function process_supports($project, &$errors = array()) { // tratar colaboraciones existentes foreach ($project->supports as $key => $support) { // quitar las colaboraciones marcadas para quitar if (!empty($_POST["support-{$support->id}-remove"])) { unset($project->supports[$key]); continue; } if (isset($_POST['support-' . $support->id . '-support'])) { $support->support = $_POST['support-' . $support->id . '-support']; $support->description = $_POST['support-' . $support->id . '-description']; $support->type = $_POST['support-' . $support->id . '-type']; if (!empty($support->thread)) { // actualizar ese mensaje $msg = Model\Message::get($support->thread); $msg->date = date('Y-m-d'); $msg->message = "{$support->support}: {$support->description}"; $msg->blocked = true; $msg->save(); } else { // grabar nuevo mensaje $msg = new Model\Message(array('user' => $project->owner, 'project' => $project->id, 'date' => date('Y-m-d'), 'message' => "{$support->support}: {$support->description}", 'blocked' => true)); if ($msg->save()) { // asignado a la colaboracion como thread inicial $support->thread = $msg->id; // Evento Feed $log = new Feed(); $log->setTarget($project->id); $log->populate('usuario pone una nueva colaboracion en su proyecto (dashboard)', '/admin/projects', \vsprintf('%s ha publicado una nueva %s en el proyecto %s, con el título "%s"', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('message', 'Colaboración'), Feed::item('project', $project->name, $project->id), Feed::item('update', $support->support, $project->id . '/messages#message' . $msg->id)))); $log->doAdmin('user'); // evento público, si el proyecto es público if ($project->status > 2) { $log->populate($_SESSION['user']->name, '/user/profile/' . $_SESSION['user']->id, Text::html('feed-new_support', Feed::item('project', $project->name, $project->id), Feed::item('update', $support->support, $project->id . '/messages#message' . $msg->id)), $_SESSION['user']->avatar->id); $log->doPublic('community'); } unset($log); } } } } // añadir nueva colaboracion (no hacemos lo del mensaje porque esta sin texto) if (!empty($_POST['support-add'])) { $new_support = new Model\Project\Support(array('project' => $project->id, 'support' => 'Nueva colaboración', 'type' => 'task', 'description' => '')); if ($new_support->save($errors)) { $project->supports[] = $new_support; $_POST['support-' . $new_support->id . '-edit'] = true; } else { $project->supports[] = new Model\Project\Support(array('project' => $project->id, 'support' => 'Nueva colaboración', 'type' => 'task', 'description' => '')); } } // guardamos los datos que hemos tratado y los errores de los datos $project->save($errors); return $project; }
* GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Goteo. If not, see <http://www.gnu.org/licenses/agpl.txt>. * */ use Goteo\Core\View, Goteo\Library\Text, Goteo\Library\SuperForm; $project = $this['project']; $errors = $this['errors']; $supports = array(); if (!empty($project->supports)) { foreach ($project->supports as $support) { $ch = array(); // a ver si es el que estamos editando o no if (!empty($this["support-{$support->id}-edit"])) { $original = \Goteo\Model\Project\Support::get($support->id); // a este grupo le ponemos estilo de edicion $supports["support-{$support->id}"] = array('type' => 'group', 'class' => 'support editsupport', 'children' => array("support-{$support->id}-support-orig" => array('title' => Text::get('supports-field-support'), 'type' => 'html', 'html' => $original->support), "support-{$support->id}-support" => array('title' => '', 'type' => 'textbox', 'size' => 100, 'class' => 'inline', 'value' => $support->support, 'errors' => !empty($errors["support-{$support->id}-support"]) ? array($errors["support-{$support->id}-support"]) : array(), 'ok' => !empty($okeys["support-{$support->id}-support"]) ? array($okeys["support-{$support->id}-support"]) : array(), 'hint' => Text::get('tooltip-project-support-support')), "support-{$support->id}-description-orig" => array('title' => Text::get('supports-field-description'), 'type' => 'html', 'html' => nl2br($original->description)), "support-{$support->id}-description" => array('type' => 'textarea', 'title' => '', 'cols' => 100, 'rows' => 4, 'class' => 'inline support-description', 'value' => $support->description, 'errors' => !empty($errors["support-{$support->id}-description"]) ? array($errors["support-{$support->id}-description"]) : array(), 'ok' => !empty($okeys["support-{$support->id}-description"]) ? array($okeys["support-{$support->id}-description"]) : array(), 'hint' => Text::get('tooltip-project-support-description')), "support-{$support->id}-buttons" => array('type' => 'group', 'class' => 'buttons', 'children' => array("support-{$support->id}-ok" => array('type' => 'submit', 'label' => Text::get('form-accept-button'), 'class' => 'inline ok'))))); } else { $supports["support-{$support->id}"] = array('class' => 'support', 'view' => 'view/dashboard/translates/supports/support.html.php', 'data' => array('support' => $support)); } } } $sfid = 'sf-project-supports'; ?> <form method="post" action="/dashboard/translates/supports/save" class="project" enctype="multipart/form-data"> <?php echo new SuperForm(array('id' => $sfid, 'action' => '', 'level' => 3, 'method' => 'post', 'title' => '', 'hint' => Text::get('guide-project-supports'), 'class' => 'aqua', 'footer' => array('view-step-preview' => array('type' => 'submit', 'name' => 'save-supports', 'label' => Text::get('regular-save'), 'class' => 'next')), 'elements' => array('process_supports' => array('type' => 'hidden', 'value' => 'supports'), 'supports' => array('type' => 'group', 'title' => Text::get('supports-fields-support-title'), 'hint' => Text::get('tooltip-project-supports'), 'children' => $supports)))); ?>
echo new View('view/project/widget/rewards.html.php', array('project' => $project)); } echo new View('view/user/widget/user.html.php', array('user' => $project->user)); ?> </div> <?php $printSendMsg = false; ?> <div class="center"> <?php // los modulos centrales son diferentes segun el show switch ($show) { case 'needs': if ($this['non-economic']) { echo new View('view/project/widget/non-needs.html.php', array('project' => $project, 'types' => Support::types())); } else { echo new View('view/project/widget/needs.html.php', array('project' => $project, 'types' => Cost::types())), new View('view/project/widget/schedule.html.php', array('project' => $project)), new View('view/project/widget/sendMsg.html.php', array('project' => $project)); } break; case 'supporters': // segun el paso de aporte if (!empty($step) && in_array($step, array('start', 'login', 'confirm', 'continue', 'ok', 'fail'))) { switch ($step) { case 'continue': echo new View('view/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)), new View('view/project/widget/invest_redirect.html.php', array('project' => $project, 'personal' => $personalData, 'step' => $step, 'allowpp' => $this['allowpp'])); break; case 'ok': echo new View('view/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)), new View('view/project/widget/spread.html.php', array('project' => $project)); //sacarlo de div#center $printSendMsg = true;
public function projects($option = 'summary', $action = 'list', $id = null) { $user = $_SESSION['user']; $errors = array(); // verificación de proyectos y proyecto de trabajo list($project, $projects) = Dashboard\Projects::verifyProject($user, $action); // teniendo proyecto de trabajo, comprobar si el proyecto esta en estado de tener blog if ($option == 'updates') { $blog = Dashboard\Projects::verifyBlog($project); } // sacaexcel de cofinanciadores if ($option == 'rewards' && $action == 'table') { $response = new \Goteo\Controller\Sacaexcel(); return $response->index('investors', $project->id); } // ojo si no tiene retornos if ($option == 'commons' && empty($project->social_rewards)) { Message::Error('Este proyecto no tiene retornos colectivos'); throw new Redirection('/dashboard/projects/'); } // procesamiento de formularios if ($_SERVER['REQUEST_METHOD'] == 'POST') { switch ($option) { // gestionar retornos (o mensaje a los mensajeros) case 'messegers': case 'rewards': // sacamos del post el filtro y el orden if ($action == 'filter') { $_SESSION['dashboard-rewards-filter'] = isset($_POST['filter']) ? $_POST['filter'] : $_SESSION['dashboard-rewards-filter']; $_SESSION['dashboard-rewards-order'] = isset($_POST['order']) ? $_POST['order'] : $_SESSION['dashboard-rewards-order']; } //procesamos el envio de mails if ($action == 'message') { Dashboard\Projects::process_mailing($option, $project); // y lo devolvemos a donde estaba throw new Redirection('/dashboard/projects/' . $option); } break; // colaboraciones // colaboraciones case 'supports': if ($action == 'save') { $project = Dashboard\Projects::process_supports($project, $errors); } break; case 'updates': // verificación: si no llega blog correcto no lo procesamos if (empty($_POST['blog']) || $_POST['blog'] != $blog->id) { throw new Redirection('/dashboard/projects/summary'); } list($action, $id) = Dashboard\Projects::process_updates($action, $project, $errors); break; } } // SubControlador para add, edit, delete y list // devuelve $post en las acciones add y edit y $posts en delete y list // maneja por referencia $action, $posts y $errors if ($option == 'updates') { list($post, $posts) = Dashboard\Projects::prepare_updates($action, $id, $blog->id); } // view data basico para esta seccion $viewData = array('menu' => self::menu(), 'section' => __FUNCTION__, 'option' => $option, 'action' => $action, 'projects' => $projects, 'errors' => $errors); switch ($option) { case 'summary': // los datos json de invests y visitors_data $viewData['data'] = Dashboard\Projects::graph($project->id); break; // gestionar recompensas // gestionar recompensas case 'rewards': // recompensas ofrecidas $viewData['rewards'] = Model\Project\Reward::getAll($project->id, 'individual', LANG); // aportes para este proyecto $viewData['invests'] = Model\Invest::getAll($project->id); // ver por (esto son orden y filtros) $viewData['filter'] = $_SESSION['dashboard-rewards-filter']; $viewData['order'] = $_SESSION['dashboard-rewards-order']; break; // gestionar retornos // gestionar retornos case 'commons': $icons = Model\Icon::getAll('social'); foreach ($icons as $key => $icon) { $icons[$key] = $icon->name; } $viewData['icons'] = $icons; break; // listar mensajeadores // listar mensajeadores case 'messegers': $viewData['messegers'] = Model\Message::getMessegers($project->id); break; // editar colaboraciones // editar colaboraciones case 'supports': $viewData['types'] = Model\Project\Support::types(); // para mantener registros desplegados if ($_POST) { foreach ($_POST as $k => $v) { if (!empty($v) && preg_match('/support-(\\d+)-edit/', $k, $r)) { $viewData[$k] = true; break; } } } if (!empty($_POST['support-add'])) { $last = end($project->supports); if ($last !== false) { $viewData['support-' . $last->id . '-edit'] = true; } } $project->supports = Model\Project\Support::getAll($project->id); break; // publicar actualizaciones // publicar actualizaciones case 'updates': $viewData['blog'] = $blog; $viewData['posts'] = $posts; $viewData['post'] = $post; break; } $viewData['project'] = $project; return new View('view/dashboard/index.html.php', $viewData); }
/** * actualiza en la tabla los datos del proyecto * @param array $project->errors para guardar los errores de datos del formulario, los errores de proceso se guardan en $project->errors['process'] */ public function save(&$errors = array()) { if ($this->dontsave) { return false; } if (!$this->validate($errors)) { return false; } try { // fail para pasar por todo antes de devolver false $fail = false; // los nif sin guiones, espacios ni puntos $this->contract_nif = str_replace(array('_', '.', ' ', '-', ',', ')', '('), '', $this->contract_nif); $this->entity_cif = str_replace(array('_', '.', ' ', '-', ',', ')', '('), '', $this->entity_cif); // Image if (is_array($this->image) && !empty($this->image['name'])) { $image = new Image($this->image); if ($image->save($errors)) { $this->gallery[] = $image; $this->image = $image->id; /** * Guarda la relación NM en la tabla 'project_image'. */ if (!empty($image->id)) { self::query("REPLACE project_image (project, image) VALUES (:project, :image)", array(':project' => $this->id, ':image' => $image->id)); } } } $fields = array('contract_name', 'contract_nif', 'contract_email', 'contract_entity', 'contract_birthdate', 'entity_office', 'entity_name', 'entity_cif', 'phone', 'address', 'zipcode', 'location', 'country', 'secondary_address', 'post_address', 'post_zipcode', 'post_location', 'post_country', 'name', 'subtitle', 'image', 'description', 'motivation', 'video', 'video_usubs', 'about', 'goal', 'related', 'reward', 'keywords', 'media', 'media_usubs', 'currently', 'project_location', 'scope', 'resource', 'comment', 'evaluation'); $set = ''; $values = array(); foreach ($fields as $field) { if ($set != '') { $set .= ', '; } $set .= "{$field} = :{$field}"; $values[":{$field}"] = $this->{$field}; } // Solamente marcamos updated cuando se envia a revision desde el superform o el admin // $set .= ", updated = :updated"; // $values[':updated'] = date('Y-m-d'); $values[':id'] = $this->id; $sql = "UPDATE project SET " . $set . " WHERE id = :id"; if (!self::query($sql, $values)) { $errors[] = $sql . '<pre>' . print_r($values, 1) . '</pre>'; $fail = true; } // echo "$sql<br />"; // y aquí todas las tablas relacionadas // cada una con sus save, sus new y sus remove // quitar las que tiene y no vienen // añadir las que vienen y no tiene //categorias $tiene = Project\Category::get($this->id); $viene = $this->categories; $quita = array_diff_assoc($tiene, $viene); $guarda = array_diff_assoc($viene, $tiene); foreach ($quita as $key => $item) { $category = new Project\Category(array('id' => $item, 'project' => $this->id)); if (!$category->remove($errors)) { $fail = true; } } foreach ($guarda as $key => $item) { if (!$item->save($errors)) { $fail = true; } } // recuperamos las que le quedan si ha cambiado alguna if (!empty($quita) || !empty($guarda)) { $this->categories = Project\Category::get($this->id); } //skills $tiene = Project\Skill::get($this->id); $viene = $this->skills; $quita = array_diff_assoc($tiene, $viene); $guarda = array_diff_assoc($viene, $tiene); foreach ($quita as $key => $item) { $skill = new Project\Skill(array('id' => $item, 'project' => $this->id)); if (!$skill->remove($errors)) { $fail = true; } } foreach ($guarda as $key => $item) { if (!$item->save($errors)) { $fail = true; } } // recuperamos las que le quedan si ha cambiado alguna if (!empty($quita) || !empty($guarda)) { $this->skills = Project\Skill::get($this->id); } //costes $tiene = Project\Cost::getAll($this->id); $viene = $this->costs; $quita = array_diff_key($tiene, $viene); $guarda = array_diff_key($viene, $tiene); foreach ($quita as $key => $item) { if (!$item->remove($errors)) { $fail = true; } else { unset($tiene[$key]); } } foreach ($guarda as $key => $item) { if (!$item->save($errors)) { $fail = true; } } /* Ahora, los que tiene y vienen. Si el contenido es diferente, hay que guardarlo*/ foreach ($tiene as $key => $row) { // a ver la diferencia con el que viene if ($row != $viene[$key]) { if (!$viene[$key]->save($errors)) { $fail = true; } } } if (!empty($quita) || !empty($guarda)) { $this->costs = Project\Cost::getAll($this->id); } // recalculo de minmax $this->minmax(); //retornos colectivos $tiene = Project\Reward::getAll($this->id, 'social'); $viene = $this->social_rewards; $quita = array_diff_key($tiene, $viene); $guarda = array_diff_key($viene, $tiene); foreach ($quita as $key => $item) { if (!$item->remove($errors)) { $fail = true; } else { unset($tiene[$key]); } } foreach ($guarda as $key => $item) { if (!$item->save($errors)) { $fail = true; } } /* Ahora, los que tiene y vienen. Si el contenido es diferente, hay que guardarlo*/ foreach ($tiene as $key => $row) { // a ver la diferencia con el que viene if ($row != $viene[$key]) { if (!$viene[$key]->save($errors)) { $fail = true; } } } if (!empty($quita) || !empty($guarda)) { $this->social_rewards = Project\Reward::getAll($this->id, 'social'); } //recompenssas individuales $tiene = Project\Reward::getAll($this->id, 'individual'); $viene = $this->individual_rewards; $quita = array_diff_key($tiene, $viene); $guarda = array_diff_key($viene, $tiene); foreach ($quita as $key => $item) { if (!$item->remove($errors)) { $fail = true; } else { unset($tiene[$key]); } } foreach ($guarda as $key => $item) { if (!$item->save($errors)) { $fail = true; } } /* Ahora, los que tiene y vienen. Si el contenido es diferente, hay que guardarlo*/ foreach ($tiene as $key => $row) { // a ver la diferencia con el que viene if ($row != $viene[$key]) { if (!$viene[$key]->save($errors)) { $fail = true; } } } if (!empty($quita) || !empty($guarda)) { $this->individual_rewards = Project\Reward::getAll($this->id, 'individual'); } // colaboraciones $tiene = Project\Support::getAll($this->id); $viene = $this->supports; $quita = array_diff_key($tiene, $viene); // quitar los que tiene y no viene $guarda = array_diff_key($viene, $tiene); // añadir los que viene y no tiene foreach ($quita as $key => $item) { if (!$item->remove($errors)) { $fail = true; } else { unset($tiene[$key]); } } foreach ($guarda as $key => $item) { if (!$item->save($errors)) { $fail = true; } } /* Ahora, los que tiene y vienen. Si el contenido es diferente, hay que guardarlo*/ foreach ($tiene as $key => $row) { // a ver la diferencia con el que viene if ($row != $viene[$key]) { if (!$viene[$key]->save($errors)) { $fail = true; } } } if (!empty($quita) || !empty($guarda)) { $this->supports = Project\Support::getAll($this->id); } //listo return !$fail; } catch (\PDOException $e) { $errors[] = Text::_('No se ha grabado correctamente. ') . $e->getMessage(); //Text::get('save-project-fail'); return false; } }