function create_recipe() { $recipe = new Recipe(); $this->db->insert('recipes', $_POST['recipe']); $recipe = $recipe->where('title', $_POST['recipe']['title'])->get(); $tags = explode(" ",$_POST['tags']); // create tag entries in db, save relationship // would be nice to put in a model method maybe? foreach($tags as $tag) { echo "now creating $tag"; $t = new Tag(); $t->where('name', $tag)->get(); if (!$t->exists()) { // save only if new $t->name = $tag; $t->save(); } $recipe->save($t); } $this->load->view('recipes/thankyou'); }
function index() { list($params, $id, $slug) = $this->parse_params(func_get_args()); // Create or update if ($this->method != 'get') { $c = new Content(); switch ($this->method) { case 'post': case 'put': if ($this->method == 'put') { // Update $c->get_by_id($id); if (!$c->exists()) { $this->error('404', "Content with ID: {$id} not found."); return; } $c->old_published_on = $c->published_on; $c->old_captured_on = $c->captured_on; $c->old_uploaded_on = $c->uploaded_on; if (isset($_POST['slug'])) { $c->current_slug = $c->slug; } } if (isset($_REQUEST['name'])) { if (isset($_REQUEST['upload_session_start'])) { $s = new Setting(); $s->where('name', 'last_upload')->get(); if ($s->exists() && $s->value != $_REQUEST['upload_session_start']) { $s->value = $_REQUEST['upload_session_start']; $s->save(); } } $file_name = $c->clean_filename($_REQUEST['name']); $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; $tmp_dir = FCPATH . 'storage' . DIRECTORY_SEPARATOR . 'tmp'; $tmp_path = $tmp_dir . DIRECTORY_SEPARATOR . $file_name; make_child_dir($tmp_dir); if ($chunks == 0 || $chunk == $chunks - 1) { if (isset($_REQUEST['text'])) { $path = FCPATH . 'storage' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR; $internal_id = false; } else { if (isset($_REQUEST['plugin'])) { $info = pathinfo($_REQUEST['name']); $path = FCPATH . 'storage' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $_REQUEST['plugin'] . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR; $file_name = $_REQUEST['basename'] . '.' . $info['extension']; $internal_id = false; } else { list($internal_id, $path) = $c->generate_internal_id(); } } if ($path) { $path .= $file_name; if ($chunks == 0) { $tmp_path = $path; } } else { $this->error('500', 'Unable to create directory for upload.'); return; } } // Look for the content type header if (isset($_SERVER["HTTP_CONTENT_TYPE"])) { $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; } else { if (isset($_SERVER["CONTENT_TYPE"])) { $contentType = $_SERVER["CONTENT_TYPE"]; } else { $contentType = ''; } } if (strpos($contentType, "multipart") !== false) { if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { $out = fopen($tmp_path, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen($_FILES['file']['tmp_name'], "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { $this->error('500', 'Unable to read input stream.'); return; } fclose($out); unlink($_FILES['file']['tmp_name']); } else { $this->error('500', 'Unable to write to output file.'); return; } } else { $this->error('500', 'Unable to move uploaded file.'); return; } } else { $out = fopen($tmp_path, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { $this->error('500', 'Unable to read uploaded file.'); return; } fclose($out); } else { $this->error('500', 'Unable to open output stream.'); return; } } if ($chunk < $chunks - 1) { // Don't continue until all chunks are uploaded exit; } else { if ($chunks > 0) { // Done, move to permanent location and save to DB rename($tmp_path, $path); } } if (!$internal_id) { // Custom text uploads can stop here die(json_encode(array('filename' => $file_name))); } $from = array(); $from['filename'] = $file_name; $from['internal_id'] = $internal_id; $from['file_modified_on'] = time(); } else { if (isset($_POST['localfile'])) { $filename = basename($_REQUEST['localfile']); list($internal_id, $path) = $c->generate_internal_id(); if (!file_exists($_REQUEST['localfile'])) { $this->error('500', '"localfile" does not exist.'); return; } if ($path) { $path .= $filename; } else { $this->error('500', 'Unable to create directory for upload.'); return; } copy($_REQUEST['localfile'], $path); $from = array(); $from['filename'] = $filename; $from['internal_id'] = $internal_id; $from['file_modified_on'] = time(); } else { if (isset($_POST['from_url'])) { $filename = basename($_POST['from_url']); list($internal_id, $path) = $c->generate_internal_id(); if ($path) { $path .= $filename; } else { $this->error('500', 'Unable to create directory for upload.'); return; } if ($this->_download(urldecode($_POST['from_url']), $path, true) && file_exists($path)) { $from = array(); $from['filename'] = $filename; $from['internal_id'] = $internal_id; $from['file_modified_on'] = time(); } else { $this->error('500', 'Unable to import file from provided URL.'); return; } } else { if (is_null($id)) { $this->error('403', 'New content records must be accompanied by an upload.'); return; } } } } if (isset($from)) { $from = array_merge($_POST, $from); } else { $from = $_POST; } if (isset($_REQUEST['rotate']) && is_numeric($_REQUEST['rotate']) && $c->exists()) { $r = $_REQUEST['rotate']; if (abs($r) != 90) { $this->error('403', 'Rotation can only be done in multiples of 90.'); return; } if (empty($c->storage_url)) { $path = $c->path_to_original(); $info = pathinfo($path); $midsize_path = preg_replace('/\\.' . $info['extension'] . '$/', '.1600.' . $info['extension'], $path); if (file_exists($midsize_path)) { $midsize = $midsize_path; } } else { $path = tempnam(sys_get_temp_dir(), 'original'); file_put_contents($path, file_get_contents($c->storage_url)); if (!empty($c->storage_url_midsize)) { $midsize = tempnam(sys_get_temp_dir(), 'midsize'); file_put_contents($midsize, file_get_contents($c->storage_url_midsize)); } } $s = new Setting(); $s->where('name', 'image_processing_library')->get(); include_once FCPATH . 'app' . DIRECTORY_SEPARATOR . 'koken' . DIRECTORY_SEPARATOR . 'DarkroomUtils.php'; $d = DarkroomUtils::init($s->value); $d->rotate($path, $r); if (isset($midsize)) { $d->rotate($midsize, $r); } if (!empty($c->storage_url)) { $key = $c->path . '/' . $c->filename; Shutter::store_original($path, $c->path . '/' . $c->filename); unlink($path); if (isset($midsize)) { $info = pathinfo($key); $key = preg_replace('/\\.' . $info['extension'] . '$/', '.1600.' . $info['extension'], $key); Shutter::store_original($midsize, $key); unlink($midsize); } } $c->clear_cache(); $from['width'] = $c->height; $from['height'] = $c->width; $from['aspect_ratio'] = $from['width'] / $from['height']; $from['file_modified_on'] = time(); } if (isset($_REQUEST['reset_internal_id']) && $_REQUEST['reset_internal_id'] && $c->exists()) { list($from['internal_id'], ) = $c->generate_internal_id(true); } $hook = 'content.' . ($id ? 'update' : 'create'); if (isset($from['filename']) && $id) { $c->clear_cache(); $hook .= '_with_upload'; $c->_before(); } $from = Shutter::filter("api.{$hook}", array_merge($from, array('id' => $id, 'file' => isset($path) ? $path : $c->path_to_original()))); unset($from['file']); try { $c->from_array($from, array(), true); } catch (Exception $e) { $this->error('400', $e->getMessage()); return; } if (isset($_POST['tags'])) { $c->_format_tags($_POST['tags']); } else { if ($this->method === 'put' && isset($_POST['visibility'])) { $c->_update_tag_counts(); } } $c->_readify(); $content = $c->to_array(array('auth' => true)); if ($hook === 'content.create' || $hook === 'content.update_with_upload') { if (ENVIRONMENT === 'production') { $this->load->library('mcurl'); if ($this->mcurl->is_enabled()) { $options = array(CURLOPT_HTTPHEADER => array('Connection: Close', 'Keep-Alive: 0')); $this->mcurl->add_call('normal', 'get', $content['presets']['medium_large']['url'], array(), $options); $this->mcurl->add_call('cropped', 'get', $content['presets']['medium_large']['cropped']['url'], array(), $options); $this->mcurl->execute(); } } $external_storage_url = Shutter::store_original($c->path_to_original(), str_replace('/storage/originals/', '', $content['original']['relative_url'])); if ($external_storage_url) { unlink($c->path_to_original()); $o = new Content(); $o->where('id', $content['id'])->update(array('storage_url' => $external_storage_url)); $content['storage_url'] = $external_storage_url; } } Shutter::hook($hook, $content); // Important to prevent failures from Lr plugin header('Connection: close'); $this->redirect("/content/{$c->id}" . (isset($params['context']) ? '/context:' . $params['context'] : '')); break; case 'delete': if (is_null($id)) { $this->error('403', 'Required parameter "id" not present.'); return; } else { $t = new Tag(); if (is_numeric($id)) { $content = $c->get_by_id($id); if ($c->exists()) { $trash = new Trash(); $this->db->query("DELETE from {$trash->table} WHERE id = 'content-{$c->id}'"); $c->do_delete(); } else { $this->error('404', "Content with ID: {$id} not found."); return; } } else { $is_trash = $id === 'trash'; if ($id === 'trash') { $id = array(); $trash = new Trash(); $trash->like('id', 'content-')->select_func('REPLACE', '@id', 'content-', '', 'actual_id')->get_iterated(); foreach ($trash as $item) { $id[] = (int) $item->actual_id; } } else { $id = explode(',', $id); } /* Multiple delete /content/n1/n2/n3 */ // Keep track of tags to -- $tags = array(); $c->where_in('id', $id); $contents = $c->get_iterated(); $trash = new Trash(); foreach ($contents as $c) { if ($c->exists()) { $tags = array_merge($tags, $c->tags); $this->db->query("DELETE from {$trash->table} WHERE id = 'content-{$c->id}'"); $c->do_delete(); } } } } exit; break; } } $c = new Content(); if ($slug || isset($id) && strpos($id, ',') === false) { $options = array('context' => false, 'neighbors' => false); $options = array_merge($options, $params); $original_context = $options['context']; if ($options['context'] && !in_array($options['context'], array('stream', 'favorites', 'features')) && strpos($options['context'], 'tag-') !== 0 && strpos($options['context'], 'category-') !== 0) { if (is_numeric($options['context'])) { $context_field = 'id'; } else { $context_field = 'slug'; $options['context'] = str_replace('slug-', '', $options['context']); } $a = new Album(); $a->group_start()->where($context_field, $options['context'])->or_where('internal_id', $options['context'])->group_end()->get(); $c->include_join_fields()->where_related_album('id', $a->id); } $with_token = false; if (is_numeric($id)) { $content = $c->where('deleted', 0)->get_by_id($id); } else { if ($slug) { $content = $c->where('deleted', 0)->group_start()->where('internal_id', $slug)->or_where('slug', $slug)->or_like('old_slug', ',' . $slug . ',', 'both')->group_end()->get(); } else { $content = $c->where('deleted', 0)->where('internal_id', $id)->get(); } if ($content->exists() && $content->internal_id === (is_null($id) ? $slug : $id)) { $with_token = true; } } if ($content->exists()) { if ($c->visibility == 1 && !$this->auth && !$with_token || !$this->auth && !is_numeric($id) && $c->visibility == 2) { $this->error('403', 'Private content.'); return; } $options['auth'] = $this->auth; if ($options['neighbors']) { // Make sure $neighbors is at least 2 $options['neighbors'] = max($options['neighbors'], 2); // Make sure neighbors is even if ($options['neighbors'] & 1 != 0) { $options['neighbors']++; } $options['neighbors'] = $options['neighbors'] / 2; $single_neighbors = false; } else { $options['neighbors'] = 1; $single_neighbors = true; } if ($options['context'] && !in_array($original_context, array('stream', 'favorites', 'features')) && strpos($original_context, 'tag-') !== 0 && strpos($original_context, 'category-') !== 0) { $options['in_album'] = $a; } $final = $content->to_array($options); if ($options['context']) { // TODO: Performance check $next = new Content(); $prev = new Content(); $in_a = new Album(); $next->where('deleted', 0); $prev->where('deleted', 0); $options['context'] = urldecode($options['context']); if (!in_array($original_context, array('stream', 'favorites', 'features')) && strpos($original_context, 'tag-') !== 0 && strpos($original_context, 'category-') !== 0) { if (!isset($options['context_order'])) { list($options['context_order'], $options['context_order_direction']) = explode(' ', $a->sort); } $final['context']['album'] = $a->to_array(array('auth' => $this->auth || $options['context'] === $a->internal_id)); $in_a->where("{$context_field} !=", $options['context']); $next->where_related_album('id', $a->id); $prev->where_related_album('id', $a->id); if ($options['context_order'] === 'manual') { $next->order_by_join_field('album', 'order', 'ASC')->group_start()->where_join_field('album', 'order >', $content->join_order)->or_group_start()->where_join_field('album', 'order', $content->join_order)->where_join_field('album', 'id >', $content->join_id)->group_end()->group_end(); $prev->order_by_join_field('album', 'order', 'DESC')->group_start()->where_join_field('album', 'order <', $content->join_order)->or_group_start()->where_join_field('album', 'order', $content->join_order)->where_join_field('album', 'id <', $content->join_id)->group_end()->group_end(); } else { $next_operator = strtolower($options['context_order_direction']) === 'desc' ? '<' : '>'; $prev_operator = $next_operator === '<' ? '>' : '<'; $next->group_start()->where($options['context_order'] . " {$next_operator}", $content->{$options['context_order']})->or_group_start()->where($options['context_order'], $content->{$options['context_order']})->where("id {$next_operator}", $content->id)->group_end()->group_end(); $prev->group_start()->where($options['context_order'] . " {$prev_operator}", $content->{$options['context_order']})->or_group_start()->where($options['context_order'], $content->{$options['context_order']})->where("id {$prev_operator}", $content->id)->group_end()->group_end(); } if (!$this->auth) { $next->where('visibility <', $final['context']['album']['visibility'] < 1 ? 1 : 2); $prev->where('visibility <', $final['context']['album']['visibility'] < 1 ? 1 : 2); } $in_album = $a; $final['context']['type'] = 'album'; $final['context']['title'] = $a->title; $final['context']['__koken_url'] = $final['context']['album']['__koken_url']; $final['context']['url'] = $final['context']['album']['url']; } else { if (!isset($options['context_order'])) { $options['context_order'] = 'captured_on'; $options['context_order_direction'] = 'DESC'; } else { if ($options['context_order'] === 'manual' && $original_context === 'favorites') { $options['context_order'] = 'favorite_order'; $options['context_order_direction'] = 'ASC'; } else { if ($options['context_order'] === 'manual' && $original_context === 'features') { $options['context_order'] = 'featured_order'; $options['context_order_direction'] = 'ASC'; } } } $next_operator = strtolower($options['context_order_direction']) === 'desc' ? '<' : '>'; $prev_operator = $next_operator === '<' ? '>' : '<'; $next->group_start()->where($options['context_order'] . " {$next_operator}", $content->{$options['context_order']})->or_group_start()->where($options['context_order'], $content->{$options['context_order']})->where("id {$next_operator}", $content->id)->group_end()->group_end(); $prev->group_start()->where($options['context_order'] . " {$prev_operator}", $content->{$options['context_order']})->or_group_start()->where($options['context_order'], $content->{$options['context_order']})->where("id {$prev_operator}", $content->id)->group_end()->group_end(); if (strpos($original_context, 'tag-') === 0) { $tag = str_replace('tag-', '', urldecode($original_context)); $t = new Tag(); $t->where('name', $tag)->get(); if ($t->exists()) { $next->where_related_tag('id', $t->id); $prev->where_related_tag('id', $t->id); $final['context']['type'] = 'tag'; $final['context']['title'] = $tag; $final['context']['slug'] = $tag; $t->model = 'tag_contents'; $t->slug = $t->name; $url = $t->url(); if ($url) { list($final['context']['__koken_url'], $final['context']['url']) = $url; } } } else { if (strpos($original_context, 'category-') === 0) { $category = str_replace('category-', '', $original_context); $cat = new Category(); $cat->where('slug', $category)->get(); if ($cat->exists()) { $next->where_related_category('id', $cat->id); $prev->where_related_category('id', $cat->id); $final['context']['type'] = 'category'; $final['context']['title'] = $cat->title; $final['context']['slug'] = $cat->slug; $cat->model = 'category_contents'; $url = $cat->url(); if ($url) { list($final['context']['__koken_url'], $final['context']['url']) = $url; } } } else { if ($original_context === 'favorites') { $url_data = $prev->get_data(); $urls = $prev->form_urls(); $next->where('favorite', 1); $prev->where('favorite', 1); $final['context']['type'] = 'favorite'; $final['context']['title'] = $url_data['favorite']['plural']; $final['context']['__koken_url'] = $urls['favorites']; if ($final['context']['__koken_url']) { $final['context']['url'] = $prev->get_base() . $final['context']['__koken_url'] . (defined('DRAFT_CONTEXT') && !is_numeric(DRAFT_CONTEXT) ? '&preview=' . DRAFT_CONTEXT : ''); } } else { if ($original_context === 'features') { $url_data = $prev->get_data(); $urls = $prev->form_urls(); $next->where('featured', 1); $prev->where('featured', 1); $final['context']['type'] = 'feature'; $final['context']['title'] = $url_data['feature']['plural']; $final['context']['__koken_url'] = isset($urls['features']) ? $urls['features'] : false; if ($final['context']['__koken_url']) { $final['context']['url'] = $prev->get_base() . $final['context']['__koken_url'] . (defined('DRAFT_CONTEXT') && !is_numeric(DRAFT_CONTEXT) ? '&preview=' . DRAFT_CONTEXT : ''); } } } } } if (!$this->auth) { $next->where('visibility', 0); $prev->where('visibility', 0); } $in_album = false; } $max = $next->get_clone()->count(); $min = $prev->get_clone()->count(); $final['context']['total'] = $max + $min + 1; $final['context']['position'] = $min + 1; $pre_limit = $next_limit = $options['neighbors']; if ($min < $pre_limit) { $next_limit += $pre_limit - $min; $pre_limit = $min; } if ($max < $next_limit) { $pre_limit = min($min, $pre_limit + ($next_limit - $max)); $next_limit = $max; } $final['context']['previous'] = array(); $final['context']['next'] = array(); if ($next_limit > 0) { if ($options['context_order'] !== 'manual') { $next->order_by($options['context_order'] . ' ' . $options['context_order_direction'] . ', id ' . $options['context_order_direction']); } $next->limit($next_limit)->get_iterated(); foreach ($next as $c) { $final['context']['next'][] = $c->to_array(array('auth' => $this->auth, 'in_album' => $in_album, 'context' => $original_context)); } } if ($pre_limit > 0) { if ($options['context_order'] !== 'manual') { $dir = strtolower($options['context_order_direction']) === 'desc' ? 'asc' : 'desc'; $prev->order_by($options['context_order'] . ' ' . $dir . ', id ' . $dir); } $prev->limit($pre_limit)->get_iterated(); foreach ($prev as $c) { $final['context']['previous'][] = $c->to_array(array('auth' => $this->auth, 'in_album' => $in_album, 'context' => $original_context)); } $final['context']['previous'] = array_reverse($final['context']['previous']); } } } else { $this->error('404', "Content with ID: {$id} not found."); return; } } else { if (isset($params['custom'])) { $final = $c->to_array_custom($params['custom']); } else { $c->where('deleted', 0); $params['auth'] = $this->auth; $final = $c->listing($params, $id); } } $this->set_response_data($final); }
/** * Updates the tags associated with the given media. * * If the image can't be resized, its web and thumbnail images will * be symlinked to the full size image to prevent broken image sources. * * @param Media $media The Media object to associate the tags with. * @param array $tags An array of tag names. */ private static function update_tags($media, $tags) { // Remove all existing tag associations Database::DELETE_FROM(TAG_RELATION_TABLE . ' WHERE image_id = ?', array($media->id)); foreach ($tags as $tag) { // Skip empty tags if (trim($tag) == '') { continue; } // Create tags which don't exist yet if (!Tag::exists($tag)) { Tag::create($tag); } $media->add_tag($tag); } }
function _format_tags($tags) { $t = new Tag(); $model = $this->model; $existing = array(); foreach ($this->tags->select('id,name')->get_iterated() as $tag) { $existing[] = $tag->name; } if (empty($tags)) { $remove = $existing; } else { $tags = koken_format_tags($tags); $add = array_diff($tags, $existing); $remove = array_diff($existing, $tags); foreach ($add as $tag) { $t->get_by_name($tag); if (!$t->exists()) { $t->name = $tag; } $t->last_used = time(); $t->save($this); $t->update_counts($this->model); } } foreach ($remove as $tag) { $t->get_by_name($tag); if ($t->exists()) { $this->delete($t); $t->update_counts($this->model); } } }
/** * Retrieve tag model by name or save if not exist * @param string $name * @return \Tag */ protected function getCreateTagModel($name) { $name = $this->valuesHandler->input('string', $name); $tagModel = new TagModel(); $tagModel->get_by_tag_name($name); if (!$tagModel->exists()) { $tagModel->tag_name = $name; $tagModel->save(); } return $tagModel; }
function index() { $defaults = array('page' => 1, 'limit' => 20, 'context_order' => 'count'); list($params, $id, $slug) = $this->parse_params(func_get_args()); $params = array_merge($defaults, $params); $t = new Tag(); if ($this->method !== 'get') { if (is_null($id)) { $this->error('400', 'ID is required.'); } $tag = $t->get_by_id($id); if ($this->method === 'delete') { $tag->delete(); exit; } else { $tag->name = $this->input->post('name'); $tag->save(); $this->redirect('/tags/' . $tag->id); } } if (!$slug && is_null($id)) { $final = $t->listing($params); } else { $slug = urldecode($slug); if ($slug) { $t->where('name', $slug)->get(); } else { $t->get_by_id($id); } $tag_array = $t->to_array(); $params['tag'] = $t->id; $params['tag_slug'] = $t->name; list($final, $counts) = $this->aggregate('tag', $params); $final['counts'] = $counts; $final = array_merge($tag_array, $final); $prev = new Tag(); $next = new Tag(); $prev->where('id !=', $t->id); $next->where('id !=', $t->id); if ($params['context_order'] === 'count') { $prev->group_start(); $prev->where_func('', array('@content_count', '+', '@text_count', '+', '@album_count', '>', $t->essay_count + $t->album_count + $t->content_count), null); $prev->or_group_start(); $prev->where_func('', array('@content_count', '+', '@text_count', '+', '@album_count', '=', $t->essay_count + $t->album_count + $t->content_count), null); $prev->where('name <', $t->name); $prev->group_end(); $prev->group_end(); $next->group_start(); $next->where_func('', array('@content_count', '+', '@text_count', '+', '@album_count', '<', $t->essay_count + $t->album_count + $t->content_count), null); $next->or_group_start(); $next->where_func('', array('@content_count', '+', '@text_count', '+', '@album_count', '=', $t->essay_count + $t->album_count + $t->content_count), null); $next->where('name >', $t->name); $next->group_end(); $next->group_end(); $prev->order_by_func('', array('@content_count', '+', '@text_count', '+', '@album_count'), 'ASC'); $next->order_by_func('', array('@content_count', '+', '@text_count', '+', '@album_count'), 'DESC'); } else { $prev->where('name <', $t->name); $next->where('name >', $t->name); } $prev->order_by('name DESC'); $next->order_by('name ASC'); $max = $next->get_clone()->count(); $min = $prev->get_clone()->count(); $final['context'] = array(); $final['context']['total'] = $max + $min + 1; $final['context']['position'] = $min + 1; $final['context']['previous'] = $final['context']['next'] = false; $prev->get(); $next->get(); if ($prev->exists()) { $final['context']['previous'] = $prev->to_array(); } if ($next->exists()) { $final['context']['next'] = $next->to_array(); } } $this->set_response_data($final); }
function listing($params, $id = false) { $sort = $this->_get_site_order('content'); $options = array('order_by' => $sort['by'], 'order_direction' => $sort['direction'], 'search' => false, 'search_filter' => false, 'tags' => false, 'tags_not' => false, 'page' => 1, 'match_all_tags' => false, 'limit' => 100, 'include_presets' => true, 'featured' => null, 'types' => false, 'auth' => false, 'favorites' => null, 'before' => false, 'after' => false, 'after_column' => 'uploaded_on', 'before_column' => 'uploaded_on', 'category' => false, 'category_not' => false, 'year' => false, 'year_not' => false, 'month' => false, 'month_not' => false, 'day' => false, 'day_not' => false, 'in_album' => false, 'reduce' => false, 'is_cover' => true, 'independent' => false); $options = array_merge($options, $params); if (isset($params['order_by']) && !isset($params['order_direction'])) { $options['order_direction'] = in_array($params['order_by'], array('title', 'filename')) ? 'ASC' : 'DESC'; } Shutter::hook('content.listing', array($this, $options)); if ($options['featured'] == 1 && !isset($params['order_by'])) { $options['order_by'] = 'featured_on'; } else { if ($options['favorites'] == 1 && !isset($params['order_by'])) { $options['order_by'] = 'favorited_on'; } } if ($options['auth']) { if (isset($options['visibility']) && $options['visibility'] !== 'album') { $values = array('public', 'unlisted', 'private'); if (in_array($options['visibility'], $values)) { $options['visibility'] = array_search($options['visibility'], $values); } else { if ($options['visibility'] === 'any') { $options['visibility'] = false; } else { $options['visibility'] = 0; } } } else { if (!isset($options['visibility']) || $options['visibility'] !== 'album') { $options['visibility'] = 0; } } } else { if ($options['in_album']) { $options['visibility'] = 'album'; } else { $options['visibility'] = 0; } } if ($options['visibility'] > 0 && $options['order_by'] === 'published_on') { $options['order_by'] = 'captured_on'; } if ($options['order_by'] == 'dimension') { $options['order_by'] = 'width * height'; } if (is_numeric($options['limit']) && $options['limit'] > 0) { $options['limit'] = min($options['limit'], 100); } else { $options['limit'] = 100; } if ($options['independent']) { $this->where_related('album', 'id', null); } if ($options['types']) { $types = explode(',', str_replace(' ', '', $options['types'])); $this->group_start(); foreach ($types as $t) { switch ($t) { case 'photo': $this->or_where('file_type', 0); break; case 'video': $this->or_where('file_type', 1); break; case 'audio': $this->or_where('file_type', 2); break; } } $this->group_end(); } if ($options['search'] && $options['search_filter'] === 'tags') { $options['tags'] = $options['search']; $options['search'] = false; } if ($options['search']) { $term = urldecode($options['search']); if ($options['search_filter']) { if ($options['search_filter'] === 'category') { $cat = new Category(); $cat->where('title', $term)->get(); if ($cat->exists()) { $this->where_related('category', 'id', $cat->id); } else { $this->where_related('category', 'id', 0); } } else { $this->group_start(); $this->like($options['search_filter'], $term, 'both'); $this->group_end(); } } else { $this->group_start(); $this->like('title', $term, 'both'); $this->or_like('caption', $term, 'both'); $t = new Tag(); $t->where('name', $term)->get(); if ($t->exists()) { $this->or_where_related('tag', 'id', $t->id); } $this->group_end(); } } else { if ($options['tags'] || $options['tags_not']) { $this->_do_tag_filtering($options); } } if (!is_null($options['featured'])) { $this->where('featured', $options['featured']); } if (!is_null($options['favorites'])) { $this->where('favorite', $options['favorites']); } if ($options['category']) { $this->where_related('category', 'id', $options['category']); } else { if ($options['category_not']) { $cat = new Content(); $cat->select('id')->where_related('category', 'id', $options['category_not'])->get_iterated(); $cids = array(); foreach ($cat as $c) { $cids[] = $c->id; } $this->where_not_in('id', $cids); } } if ($options['after']) { $this->where($options['after_column'] . ' >=', $options['after']); } if ($options['before']) { $this->where($options['before_column'] . ' <=', $options['before']); } if ($options['visibility'] === 'album') { $this->where('visibility <', $options['in_album']->visibility + 1); } else { if ($options['visibility'] !== false) { $this->where('visibility', $options['visibility']); } } if ($id) { $sql_order = "ORDER BY FIELD(id,{$id})"; $id = explode(',', $id); $this->where_in('id', $id); } if ($options['order_by'] === 'captured_on' || $options['order_by'] === 'uploaded_on' || $options['order_by'] === 'modified_on' || $options['order_by'] === 'published_on') { $bounds_order = $options['order_by']; } else { $bounds_order = 'published_on'; } $s = new Setting(); $s->where('name', 'site_timezone')->get(); $tz = new DateTimeZone($s->value); $offset = $tz->getOffset(new DateTime('now', new DateTimeZone('UTC'))); if ($offset === 0) { $shift = ''; } else { $shift = ($offset < 0 ? '-' : '+') . abs($offset); } // Do this before date filters are applied $bounds = $this->get_clone()->select('COUNT(DISTINCT ' . $this->table . '.id) as count, MONTH(FROM_UNIXTIME(' . $bounds_order . $shift . ')) as month, YEAR(FROM_UNIXTIME(' . $bounds_order . $shift . ')) as year')->group_by('month,year')->order_by('year')->get_iterated(); $dates = array(); foreach ($bounds as $b) { if (!is_numeric($b->year)) { continue; } if (!isset($dates[$b->year])) { $dates[$b->year] = array(); } $dates[$b->year][$b->month] = (int) $b->count; } if (in_array($options['order_by'], array('captured_on', 'uploaded_on', 'modified_on'))) { $date_col = $options['order_by']; } else { $date_col = 'published_on'; } if ($options['year'] || $options['year_not']) { if ($options['year_not']) { $options['year'] = $options['year_not']; $compare = ' !='; } else { $compare = ''; } $this->where('YEAR(FROM_UNIXTIME(' . $date_col . $shift . '))' . $compare, $options['year']); } if ($options['month'] || $options['month_not']) { if ($options['month_not']) { $options['month'] = $options['month_not']; $compare = ' !='; } else { $compare = ''; } $this->where('MONTH(FROM_UNIXTIME(' . $date_col . $shift . '))' . $compare, $options['month']); } if ($options['day'] || $options['day_not']) { if ($options['day_not']) { $options['day'] = $options['day_not']; $compare = ' !='; } else { $compare = ''; } $this->where('DAY(FROM_UNIXTIME(' . $date_col . $shift . '))' . $compare, $options['day']); if ($options['reduce']) { $a = new Album(); $a->select('id')->where('deleted', 0)->where('visibility', 0)->where('YEAR(FROM_UNIXTIME(' . $a->table . '.published_on' . $shift . '))', $options['year'])->where('MONTH(FROM_UNIXTIME(' . $a->table . '.published_on' . $shift . '))', $options['month'])->where('DAY(FROM_UNIXTIME(' . $a->table . '.published_on' . $shift . '))', $options['day'])->include_related('content', 'id')->get_iterated(); $ids = array(); foreach ($a as $album) { if ($album->content_id) { $ids[] = $album->content_id; } } $e = new Text(); $e->select('featured_image_id')->where('page_type', 0)->where('published', 1)->where('featured_image_id >', 0)->where('YEAR(FROM_UNIXTIME(' . $e->table . '.published_on' . $shift . '))', $options['year'])->where('MONTH(FROM_UNIXTIME(' . $e->table . '.published_on' . $shift . '))', $options['month'])->where('DAY(FROM_UNIXTIME(' . $e->table . '.published_on' . $shift . '))', $options['day'])->get_iterated(); foreach ($e as $essay) { if ($essay->featured_image_id) { $ids[] = $essay->featured_image_id; } } if (!empty($ids)) { $this->where_not_in('id', $ids); } } } $vid_count = $this->get_clone()->where('file_type', 1)->count(); $aud_count = $this->get_clone()->where('file_type', 2)->count(); $final = $this->paginate($options); $final['dates'] = $dates; $this->include_related_count('albums', NULL, array('visibility' => 0)); $this->include_related_count('categories'); if ($id && !isset($params['order_by'])) { $q = explode('LIMIT', $this->get_sql()); $query = $q[0] . $sql_order . ' LIMIT ' . $q[1]; $data = $this->query($query); } else { if ($options['order_by'] === 'title') { $q = explode('LIMIT', $this->get_sql()); $query = preg_replace('/SELECT\\s(`[^`]+`\\.\\*)/', "SELECT COALESCE(NULLIF(title, ''), filename) as order_title, \$1", $q[0]); $query .= 'ORDER BY order_title ' . $options['order_direction'] . ' LIMIT ' . $q[1]; $data = $this->query($query); } else { $data = $this->order_by($options['order_by'] . ' ' . $options['order_direction'] . ', id ' . $options['order_direction'])->get_iterated(); } } if (!$options['limit']) { $final['per_page'] = $data->result_count(); $final['total'] = $data->result_count(); } $final['counts'] = array('videos' => $vid_count, 'audio' => $aud_count, 'images' => $final['total'] - $vid_count - $aud_count, 'total' => $final['total']); $final['content'] = array(); $final['sort'] = $sort; $tag_map = $this->_eager_load_tags($data); foreach ($data as $content) { $tags = isset($tag_map['c' . $content->id]) ? $tag_map['c' . $content->id] : array(); $options['eager_tags'] = $tags; $final['content'][] = $content->to_array($options); } return $final; }
function listing($params) { $sort = $this->_get_site_order('album'); $options = array('trash' => false, 'page' => 1, 'order_by' => $sort['by'], 'order_direction' => $sort['direction'], 'search' => false, 'search_filter' => false, 'tags' => false, 'tags_not' => false, 'match_all_tags' => false, 'limit' => false, 'include_empty' => true, 'types' => false, 'featured' => false, 'category' => false, 'category_not' => false, 'year' => false, 'year_not' => false, 'month' => false, 'month_not' => false, 'day' => false, 'day_not' => false, 'flat' => false, 'reduce' => false, 'id_not' => false, 'auth' => false); $options = array_merge($options, $params); if (isset($params['order_by']) && !isset($params['order_direction'])) { $options['order_direction'] = in_array($params['order_by'], array('created_on', 'modified_on', 'published_on', 'total_count', 'image_count', 'video_count')) ? 'DESC' : 'ASC'; } $options = Shutter::filter('api.albums.listing.options', $options); Shutter::hook('albums.listing', array($this, $options)); if ($options['order_by'] === 'manual') { $options['order_by'] = 'left_id'; if (!isset($params['order_direction'])) { $options['order_direction'] = 'asc'; } } if ($options['featured'] == 1 && !isset($params['order_by'])) { $options['order_by'] = 'featured_on'; } if (!is_numeric($options['limit'])) { $options['limit'] = false; } if ($options['types']) { $types = explode(',', str_replace(' ', '', $options['types'])); $this->group_start(); foreach ($types as $t) { switch ($t) { case 'set': $this->or_where('album_type', 2); break; case 'smart': $this->or_where('album_type', 1); break; case 'standard': $this->or_where('album_type', 0); break; } } $this->group_end(); } if ($options['search'] && $options['search_filter'] === 'tags') { $options['tags'] = $options['search']; $options['search'] = false; } if ($options['search']) { $term = urldecode($options['search']); if ($options['search_filter']) { if ($options['search_filter'] === 'category') { $cat = new Category(); $cat->where('title', $term)->get(); if ($cat->exists()) { $this->where_related('category', 'id', $cat->id); } else { $this->where_related('category', 'id', 0); } } else { $this->group_start(); $this->like($options['search_filter'], $term, 'both'); $this->group_end(); } } else { $this->group_start(); $this->like('title', $term, 'both'); $this->or_like('description', $term, 'both'); $t = new Tag(); $t->where('name', $term)->get(); if ($t->exists()) { $this->or_where_related('tag', 'id', $t->id); } $this->group_end(); } } else { if ($options['tags'] || $options['tags_not']) { $this->_do_tag_filtering($options); } } if ($options['id_not']) { $this->where_not_in('id', explode(',', $options['id_not'])); } $sub_list = false; if ($this->exists()) { $sub_list = true; $this->where('left_id >', $this->left_id)->where('right_id <', $this->right_id)->where('level', $this->level + 1)->where('visibility', $this->visibility); $options['visibility'] = $this->visibility; } else { if ($options['auth']) { if (isset($options['visibility'])) { $values = array('public', 'unlisted', 'private'); if (in_array($options['visibility'], $values)) { $options['visibility'] = array_search($options['visibility'], $values); } else { $options['visibility'] = 0; } } else { $options['visibility'] = 0; } } else { $options['visibility'] = 0; } } $this->where('visibility', $options['visibility']); if ($options['visibility'] > 0 && ($options['order_by'] === 'manual' || $options['order_by'] === 'published_on')) { $options['order_by'] = 'title'; } if (!$options['include_empty']) { $this->where('total_count >', 0); } if ($options['featured'] || $options['category'] || $options['category_not']) { if ($options['featured']) { $this->where('featured', 1); } if ($options['category']) { $this->where_related('category', 'id', $options['category']); } else { if ($options['category_not']) { $cat = new Album(); $cat->select('id')->where_related('category', 'id', $options['category_not'])->get_iterated(); $cids = array(); foreach ($cat as $c) { $cids[] = $c->id; } $this->where_not_in('id', $cids); } } } else { if ($options['featured'] !== false && (int) $options['featured'] === 0) { $this->where('featured', 0); } else { if (!$sub_list && !$options['category'] && !$options['tags'] && !$options['year'] && !$options['flat']) { $this->where('level', 1); } } } if ($options['order_by'] === 'left_id' && ($options['tags'] || $options['year'])) { $options['order_by'] = 'title,id'; $options['order_direction'] = 'asc'; } if (in_array($options['order_by'], array('created_on', 'modified_on'))) { $date_col = $options['order_by']; } else { $date_col = 'published_on'; } $s = new Setting(); $s->where('name', 'site_timezone')->get(); $tz = new DateTimeZone($s->value); $offset = $tz->getOffset(new DateTime('now', new DateTimeZone('UTC'))); if ($offset === 0) { $shift = ''; } else { $shift = ($offset < 0 ? '-' : '+') . abs($offset); } if ($options['year'] || $options['year_not']) { if ($options['year_not']) { $options['year'] = $options['year_not']; $compare = ' !='; } else { $compare = ''; } $this->where('YEAR(FROM_UNIXTIME(' . $this->table . '.' . $date_col . $shift . '))' . $compare, $options['year']); } if ($options['month'] || $options['month_not']) { if ($options['month_not']) { $options['month'] = $options['month_not']; $compare = ' !='; } else { $compare = ''; } $this->where('MONTH(FROM_UNIXTIME(' . $this->table . '.' . $date_col . $shift . '))' . $compare, $options['month']); } if ($options['day'] || $options['day_not']) { if ($options['day_not']) { $options['day'] = $options['day_not']; $compare = ' !='; } else { $compare = ''; } $this->where('DAY(FROM_UNIXTIME(' . $this->table . '.' . $date_col . $shift . '))' . $compare, $options['day']); if ($options['reduce']) { $e = new Text(); $e->select('id')->where('page_type', 0)->where('published', 1)->where('YEAR(FROM_UNIXTIME(' . $this->table . '.published_on' . $shift . '))', $options['year'])->where('MONTH(FROM_UNIXTIME(' . $this->table . '.published_on' . $shift . '))', $options['month'])->where('DAY(FROM_UNIXTIME(' . $this->table . '.published_on' . $shift . '))', $options['day'])->include_related('album', 'id')->get_iterated(); $ids = array(); foreach ($e as $essay) { if ($essay->album_id) { $ids[] = $essay->album_id; } } if (!empty($ids)) { $this->where_not_in('id', $ids); } $tops = $this->get_clone()->where('album_type', 2)->get_iterated(); $lefts = array(); foreach ($tops as $set) { if ($set->right_id - $set->left_id > 1) { $lefts = array_merge($lefts, range($set->left_id + 1, $set->right_id - 1)); } } if (!empty($lefts)) { $this->where_not_in('left_id', $lefts); } } } $this->where('deleted', (int) $options['trash']); $set_count = $this->get_clone()->where('album_type', 2)->count(); $final = $this->paginate($options); $this->include_related_count('text'); $this->include_related_count('categories'); if (preg_match('/_on$/', $options['order_by'])) { $options['order_by'] .= ' ' . $options['order_direction'] . ',id ' . $options['order_direction']; } else { $options['order_by'] .= ' ' . $options['order_direction']; } $data = $this->order_by($options['order_by'])->get_iterated(); if (!$options['limit']) { $final['per_page'] = $data->result_count(); $final['total'] = $data->result_count(); } $final['counts'] = array('albums' => $final['total'] - $set_count, 'sets' => $set_count, 'total' => $final['total']); $final['albums'] = array(); $final['sort'] = $sort; $tag_map = $this->_eager_load_tags($data); foreach ($data as $album) { $tags = isset($tag_map['c' . $album->id]) ? $tag_map['c' . $album->id] : array(); $params['eager_tags'] = $tags; $params['include_parent'] = !$sub_list; $final['albums'][] = $album->to_array($params); } return $final; }
function index() { list($params, $id, $slug) = $this->parse_params(func_get_args()); $params['auth'] = $this->auth; // Create or update if ($this->method != 'get') { $t = new Text(); switch ($this->method) { case 'post': case 'put': if ($id) { $t->get_by_id($id); $t->old_published = $t->published; $t->current_slug = $t->slug; if (isset($_POST['unpublish'])) { $_POST['published'] = 0; $_POST['published_on'] = null; } } else { if (isset($_POST['page_type']) && $_POST['page_type'] === 'page') { $_POST['published'] = 1; } } $arr = $_POST; global $raw_input_data; if (isset($raw_input_data['content'])) { $arr['content'] = $raw_input_data['content']; } if (isset($raw_input_data['draft'])) { $arr['draft'] = $raw_input_data['draft']; } // Little hack here to make sure content validation is always run // (newline gets stripped in text->_format_content) if (isset($arr['content'])) { $arr['content'] .= "\n"; } try { $t->from_array($arr, array(), true); } catch (Exception $e) { $this->error('400', $e->getMessage()); return; } if (isset($_POST['tags'])) { $t->_format_tags($_POST['tags']); } else { if ($this->method === 'put' && isset($_POST['published'])) { $t->_update_tag_counts(); } } $arr = $t->to_array(array('expand' => true)); if ($id) { Shutter::hook('text.update', $arr); } else { Shutter::hook('text.create', $arr); } $this->redirect("/text/{$t->id}" . (isset($params['render']) ? '/render:' . $params['render'] : '')); break; case 'delete': if (is_null($id)) { $this->error('403', 'Required parameter "id" not present.'); return; } else { if (is_numeric($id)) { $id = array($id); } else { $id = explode(',', $id); } $tags = array(); foreach ($id as $text_id) { $text = $t->get_by_id($text_id); if ($text->exists()) { $tags = array_merge($tags, $text->tags); $s = new Slug(); $prefix = $text->page_type == 0 ? 'essay' : 'page'; $this->db->query("DELETE FROM {$s->table} WHERE id = '{$prefix}.{$text->slug}'"); Shutter::hook('text.delete', $text->to_array(array('auth' => true))); if (!$text->delete()) { // TODO: More info $this->error('500', 'Delete failed.'); return; } } } } exit; break; } } $p = new Text(); // No id, so we want a list if (is_null($id) && !$slug) { $params['state'] = 'published'; $final = $p->listing($params); } else { if (!is_null($id)) { if (is_numeric($id)) { $page = $p->get_by_id($id); } else { $this->auth = $params['auth'] = true; $page = $p->get_by_internal_id($id); } } else { if ($slug) { $p->group_start()->where('slug', $slug)->or_like('old_slug', ',' . $slug . ',', 'both')->group_end(); if (isset($params['type'])) { $p->where('page_type', $params['type'] === 'essay' ? 0 : 1); } $page = $p->get(); } } $params['expand'] = true; if ($page->exists()) { $final = $page->to_array($params); if (!$this->auth && !$final['published']) { $this->error('404', 'Not found'); return; } } else { $this->error('404', "Text with ID: {$id} not found."); return; } if ($final['page_type'] === 'essay' && $page->published) { $options = array('neighbors' => false, 'context' => false); $options = array_merge($options, $params); if ($options['neighbors']) { // Make sure $neighbors is at least 2 $options['neighbors'] = max($options['neighbors'], 2); // Make sure neighbors is even if ($options['neighbors'] & 1 != 0) { $options['neighbors']++; } $options['neighbors'] = $options['neighbors'] / 2; } else { $options['neighbors'] = 1; } if ($options['neighbors']) { // TODO: Performance check $next = new Text(); $prev = new Text(); $to_arr_options = array('auth' => $this->auth); $next->group_start()->where('page_type', 0)->where('published', 1)->group_start()->where('published_on <', $page->published_on)->or_group_start()->where('published_on =', $page->published_on)->where('id <', $page->id)->group_end()->group_end()->group_end(); $prev->group_start()->where('page_type', 0)->where('published', 1)->group_start()->where('published_on >', $page->published_on)->or_group_start()->where('published_on =', $page->published_on)->where('id >', $page->id)->group_end()->group_end()->group_end(); if (strpos($options['context'], 'tag-') === 0) { $tag = str_replace('tag-', '', urldecode($options['context'])); $t = new Tag(); $t->where('name', $tag)->get(); $to_arr_options['context'] = "tag-{$tag}"; if ($t->exists()) { $next->where_related_tag('id', $t->id); $prev->where_related_tag('id', $t->id); $final['context']['type'] = 'tag'; $final['context']['title'] = $tag; $final['context']['slug'] = $tag; $t->model = 'tag_essays'; $t->slug = $t->name; $url = $t->url(); if ($url) { list($final['context']['__koken_url'], $final['context']['url']) = $url; } } } else { if (strpos($options['context'], 'category-') === 0) { $category = str_replace('category-', '', $options['context']); $cat = new Category(); $cat->where('slug', $category)->get(); if ($cat->exists()) { $next->where_related_category('id', $cat->id); $prev->where_related_category('id', $cat->id); $final['context']['type'] = 'category'; $final['context']['title'] = $cat->title; $final['context']['slug'] = $cat->slug; $to_arr_options['context'] = "category-{$cat->id}"; $cat->model = 'category_essays'; $url = $cat->url(); if ($url) { list($final['context']['__koken_url'], $final['context']['url']) = $url; } } } } $max = $next->get_clone()->count(); $min = $prev->get_clone()->count(); $final['context']['total'] = $max + $min + 1; $final['context']['position'] = $min + 1; $pre_limit = $next_limit = $options['neighbors']; if ($min < $pre_limit) { $next_limit += $pre_limit - $min; $pre_limit = $min; } if ($max < $next_limit) { $pre_limit = min($min, $pre_limit + ($next_limit - $max)); $next_limit = $max; } $final['context']['previous'] = array(); $final['context']['next'] = array(); if ($next_limit > 0) { $next->order_by('published_on DESC, id DESC')->limit($next_limit); $next->get_iterated(); foreach ($next as $c) { $final['context']['next'][] = $c->to_array($to_arr_options); } } if ($pre_limit > 0) { $prev->order_by('published_on ASC, id ASC')->limit($pre_limit); $prev->get_iterated(); foreach ($prev as $c) { $final['context']['previous'][] = $c->to_array($to_arr_options); } $final['context']['previous'] = array_reverse($final['context']['previous']); } } } } $this->set_response_data($final); }
/** * Validation - Check if tag_id is a valid id */ public function validTag($data) { $values = array_values($data); if (!isset($values)) { return false; } $value = $values[0]; /* Load the Tag model */ App::import("Webzash.Model", "Tag"); $Tag = new Tag(); if ($Tag->exists($value)) { return true; } else { return false; } }
<?php include '../../inc/init.inc'; if ((!isset($title) || $title == "") && !isset($question_id) || (!isset($content) || $content == "")) { $res->load('questions', array()); } else { if (isset($title)) { $args['title'] = $title; } if (isset($question_id)) { $args['question_id'] = $question_id; } $args['content'] = $content; $args['user_id'] = $res->user->id; $question = Question::create($args); if (isset($tag_list_values)) { $tags = explode(',', $tag_list_values); foreach ($tags as $tagName) { $tagName = strtoupper($tagName); if (Tag::exists(array('name' => $tagName))) { $tag = Tag::find_by_name($tagName); } else { $tag = Tag::create(array('name' => $tagName)); } Questions_Tag::create(array('question_id' => $question->id, 'tag_id' => $tag->id)); } } } $res->load('question', array('id' => $question->id));