Example #1
0
 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);
 }
Example #2
0
 function index()
 {
     // TODO: Make sure user is admin over content they trash
     list($params, $id) = $this->parse_params(func_get_args());
     if ($this->method != 'get') {
         $c = new Content();
         $a = new Album();
         $t = new Trash();
         $tag = new Tag();
         $options = array('content' => array(), 'albums' => array());
         $params = array_merge($options, $params);
         if (!empty($params['content'])) {
             $params['content'] = explode(',', $params['content']);
         }
         if (!empty($params['albums'])) {
             $params['albums'] = explode(',', $params['albums']);
         }
         switch ($this->method) {
             case 'post':
                 $q = array();
                 $content_ids = array();
                 $album_ids = array();
                 $now = time();
                 if (!empty($params['content'])) {
                     $content = $c->where_in('id', $params['content'])->get_iterated();
                     foreach ($content as $c) {
                         $q[] = "('content-{$c->id}', '" . $this->db->escape_str(utf8_encode(serialize($c->to_array(array('auth' => $this->auth))))) . "', {$now})";
                     }
                 }
                 if (!empty($params['albums'])) {
                     foreach ($params['albums'] as $album_id) {
                         $al = new Album();
                         $al->get_by_id($album_id);
                         if ($al->exists()) {
                             $q[] = "('album-{$al->id}', '" . $this->db->escape_str(utf8_encode(serialize($al->to_array()))) . "', {$now})";
                             $al->tree_trash();
                             foreach ($al->categories->get_iterated() as $category) {
                                 $category->update_counts('album');
                             }
                             foreach ($al->tags->get_iterated() as $tag) {
                                 $tag->update_counts('album');
                             }
                         }
                     }
                     $a->update_set_counts();
                 }
                 if (!empty($q)) {
                     $q = join(',', $q);
                     $this->db->query("INSERT INTO {$t->table} VALUES {$q} ON DUPLICATE KEY UPDATE data = VALUES(data)");
                 }
                 if (!empty($params['content'])) {
                     $c->where_in('id', $params['content'])->update('deleted', 1);
                     $albums = $a->where_in_related('content', 'id', $params['content'])->get_iterated();
                     foreach ($albums as $a) {
                         $a->update_counts();
                     }
                     $previews = $a->where_in_related('cover', 'id', $params['content'])->distinct()->get_iterated();
                     $prefix = preg_replace('/trash$/', '', $t->table);
                     $this->db->query("DELETE FROM {$prefix}join_albums_covers WHERE cover_id IN(" . join(',', $params['content']) . ")");
                     foreach ($previews as $a) {
                         $a->reset_covers();
                     }
                     foreach ($c->where_in('id', $params['content'])->get_iterated() as $content) {
                         foreach ($content->categories->get_iterated() as $category) {
                             $category->update_counts('content');
                         }
                         foreach ($content->tags->get_iterated() as $tag) {
                             $tag->update_counts('content');
                         }
                     }
                 }
                 $this->redirect('/trash');
                 break;
             case 'delete':
                 $ids = array();
                 foreach ($params['content'] as $id) {
                     $ids[] = "'content-{$id}'";
                 }
                 foreach ($params['albums'] as $id) {
                     $ids[] = "'album-{$id}'";
                 }
                 if (!empty($ids)) {
                     $ids = join(',', $ids);
                     $this->db->query("DELETE FROM {$t->table} WHERE id IN ({$ids})");
                 }
                 if (!empty($params['albums'])) {
                     foreach ($params['albums'] as $album_id) {
                         $al = new Album();
                         $al->get_by_id($album_id);
                         if ($al->exists()) {
                             $al->tree_trash_restore();
                             foreach ($al->categories->get_iterated() as $category) {
                                 $category->update_counts('album');
                             }
                             foreach ($al->tags->get_iterated() as $tag) {
                                 $tag->update_counts('album');
                             }
                         }
                     }
                     $a->update_set_counts();
                 }
                 if (!empty($params['content'])) {
                     $c->where_in('id', $params['content'])->update('deleted', 0);
                     $covers = $a->where_in_related('cover', 'id', $params['content'])->distinct()->get_iterated();
                     foreach ($covers as $a) {
                         $a->reset_covers();
                     }
                     $albums = $a->where_in_related('content', 'id', $params['content'])->get_iterated();
                     foreach ($albums as $a) {
                         $a->update_counts();
                     }
                     foreach ($c->where_in('id', $params['content'])->get_iterated() as $content) {
                         foreach ($content->categories->get_iterated() as $category) {
                             $category->update_counts('content');
                         }
                         foreach ($content->tags->get_iterated() as $tag) {
                             $tag->update_counts('content');
                         }
                     }
                 }
                 exit;
                 break;
         }
     }
     $options = array('page' => 1, 'limit' => 100);
     $options = array_merge($options, $params);
     if (is_numeric($options['limit']) && $options['limit'] > 0) {
         $options['limit'] = min($options['limit'], 100);
     } else {
         $options['limit'] = 100;
     }
     $t = new Trash();
     $final = $t->paginate($options);
     $data = $t->order_by('created_on DESC')->get_iterated();
     $final['trash'] = array();
     foreach ($data as $member) {
         $content = unserialize(utf8_decode($member->data));
         if (!$content) {
             $content = unserialize($member->data);
         }
         if (isset($content['description'])) {
             $type = 'album';
         } else {
             $type = 'content';
         }
         if ($content) {
             $final['trash'][] = array('type' => $type, 'data' => $content);
         } else {
             $final['total']--;
         }
     }
     $this->set_response_data($final);
 }
Example #3
0
 function index()
 {
     list($params, $id, $slug) = $this->parse_params(func_get_args());
     $params['auth'] = $this->auth;
     // Create or update
     if ($this->method != 'get') {
         $a = new Album();
         switch ($this->method) {
             case 'post':
             case 'put':
                 if ($this->method == 'put') {
                     if (isset($params['order'])) {
                         $this->_order($params['order']);
                         $this->redirect("/albums");
                     } else {
                         if (is_null($id)) {
                             $this->error('403', 'Required parameter "id" not present.');
                             return;
                         }
                     }
                     // Update
                     $a->get_by_id($id);
                     if (!$a->exists()) {
                         $this->error('404', "Album with ID: {$id} not found.");
                         return;
                     }
                     $a->old_created_on = $a->created_on;
                     $a->old_published_on = $a->published_on;
                     $a->old_visibility = $a->visibility;
                     $a->current_slug = $a->slug;
                 } else {
                     if (isset($_POST['from_directory'])) {
                         // Cache this to prevent tag spillage from IPTC
                         $tags_cache = $_POST['tags'];
                         if (is_dir($_POST['from_directory'])) {
                             $_POST['tags'] = '';
                             $this->load->helper('directory', 1);
                             $files = directory_map($_POST['from_directory']);
                             $content_ids = array();
                             foreach ($files as $file) {
                                 $c = new Content();
                                 $file = $_POST['from_directory'] . DIRECTORY_SEPARATOR . $file;
                                 $filename = basename($file);
                                 list($internal_id, $path) = $c->generate_internal_id();
                                 if (file_exists($file)) {
                                     if ($path) {
                                         $path .= $filename;
                                     } else {
                                         $this->error('500', 'Unable to create directory for upload.');
                                         return;
                                     }
                                     copy($file, $path);
                                     $from = array();
                                     $from['filename'] = $filename;
                                     $from['internal_id'] = $internal_id;
                                     $from['file_modified_on'] = time();
                                     $c->from_array($from, array(), true);
                                     $content_ids[] = $c->id;
                                 }
                             }
                         }
                         $_POST['tags'] = $tags_cache;
                     }
                 }
                 // Don't allow these fields to be saved generically
                 $private = array('parent_id', 'left_id', 'right_id');
                 if ($a->exists()) {
                     $private[] = 'album_type';
                 }
                 if (isset($_REQUEST['reset_internal_id']) && $_REQUEST['reset_internal_id'] && $a->exists()) {
                     array_shift($private);
                     $_POST['internal_id'] = koken_rand();
                 } else {
                     $private[] = 'internal_id';
                 }
                 foreach ($private as $p) {
                     unset($_POST[$p]);
                 }
                 if ($a->has_db_permission('lock tables')) {
                     $s = new Slug();
                     $t = new Tag();
                     $c = new Content();
                     $cat = new Category();
                     $this->db->query("LOCK TABLE {$a->table} WRITE, {$c->table} WRITE, {$s->table} WRITE, {$t->table} WRITE, {$cat->table} WRITE, {$a->db_join_prefix}albums_content READ, {$a->db_join_prefix}albums_categories READ, {$a->db_join_prefix}albums_tags READ");
                     $locked = true;
                 } else {
                     $locked = false;
                 }
                 try {
                     $a->from_array($_POST, array(), true);
                 } catch (Exception $e) {
                     $this->error('400', $e->getMessage());
                     return;
                 }
                 if ($locked) {
                     $this->db->query('UNLOCK TABLES');
                 }
                 if (isset($_POST['tags'])) {
                     $a->_format_tags($_POST['tags']);
                 } else {
                     if ($this->method === 'put' && isset($_POST['visibility'])) {
                         $a->_update_tag_counts();
                     }
                 }
                 $arr = $a->to_array();
                 if ($this->method === 'post') {
                     Shutter::hook('album.create', $arr);
                 } else {
                     Shutter::hook('album.update', $arr);
                 }
                 if (isset($content_ids)) {
                     $clean = new Album();
                     $clean = $clean->get_by_id($a->id);
                     $clean->manage_content(join(',', $content_ids), 'post', true);
                 }
                 $this->redirect("/albums/{$a->id}");
                 break;
             case 'delete':
                 if (is_null($id)) {
                     $this->error('403', 'Required parameter "id" not present.');
                     return;
                 } else {
                     $prefix = preg_replace('/albums$/', '', $a->table);
                     if ($id === 'trash') {
                         $id = array();
                         $trash = new Trash();
                         $trash->like('id', 'album-')->select_func('REPLACE', '@id', 'album-', '', 'actual_id')->get_iterated();
                         foreach ($trash as $item) {
                             $id[] = (int) $item->actual_id;
                         }
                     } else {
                         if (is_numeric($id)) {
                             $id = array($id);
                         } else {
                             $id = explode(',', $id);
                         }
                     }
                     $tags = array();
                     // Need to loop individually here, otherwise tree can break down
                     foreach ($id as $album_id) {
                         $al = new Album();
                         $al->get_by_id($album_id);
                         if ($al->exists()) {
                             $tags = array_merge($tags, $al->tags);
                             $this->db->query("DELETE FROM {$prefix}trash WHERE id = 'album-{$al->id}'");
                             if ($al->right_id - $al->left_id > 1) {
                                 $children = new Album();
                                 $subs = $children->where('deleted', $al->deleted)->where('visibility', $al->visibility)->where('left_id >', $al->left_id)->where('right_id <', $al->right_id)->where('level >', $al->level)->get_iterated();
                                 foreach ($subs as $sub_album) {
                                     Shutter::hook('album.delete', $sub_album->to_array());
                                     $sub_album->delete();
                                 }
                             }
                             $s = new Slug();
                             $this->db->query("DELETE FROM {$s->table} WHERE id = 'album.{$al->slug}'");
                             Shutter::hook('album.delete', $al->to_array());
                             $al->delete();
                         }
                     }
                     $al->update_set_counts();
                 }
                 exit;
                 break;
         }
     }
     $a = new Album();
     // No id, so we want a list
     if (is_null($id) && !$slug) {
         $final = $a->listing($params);
     } else {
         $defaults = array('neighbors' => false, 'include_empty_neighbors' => false);
         $options = array_merge($defaults, $params);
         $with_token = false;
         if (is_numeric($id)) {
             $album = $a->where('deleted', 0)->get_by_id($id);
         } else {
             if ($slug) {
                 $album = $a->where('deleted', 0)->group_start()->where('internal_id', $slug)->or_where('slug', $slug)->or_like('old_slug', ',' . $slug . ',', 'both')->group_end()->get();
             } else {
                 $album = $a->where('deleted', 0)->where('internal_id', $id)->get();
             }
             if ($album->exists() && $album->internal_id === (is_null($id) ? $slug : $id)) {
                 $with_token = true;
             }
         }
         if (!$album->exists()) {
             $this->error('404', 'Album not found.');
             return;
         }
         if ($a->exists()) {
             if ($a->visibility > 0 && !$this->auth && !$with_token) {
                 if ($a->visibility > 1) {
                     // Private content should 404, leave no trace, etc.
                     $this->error('404', 'Album not found.');
                 } else {
                     $this->error('403', 'Private content.');
                 }
                 return;
             }
             $final = $album->to_array($params);
             $final['context'] = $album->context($options, $this->auth);
         } else {
             $this->error('404', "Album with ID: {$id} not found.");
             return;
         }
         // TODO: This history stuff won't work here anymore
         // if ($this->method == 'put')
         // {
         // 	$h = new History();
         // 	$h->message = array( 'album:update',  $a->title );
         // 	$h->save();
         // }
         // else if ($this->method == 'post')
         // {
         // 	$h = new History();
         // 	$h->message = array( 'album:create',  $a->title );
         // 	$h->save();
         // }
     }
     $this->set_response_data($final);
 }
Example #4
0
 function to_array($options = array())
 {
     $options = array_merge(array('with_covers' => true, 'auth' => false), $options);
     $koken_url_info = $this->config->item('koken_url_info');
     $exclude = array('deleted', 'total_count', 'video_count', 'featured_order', 'tags_old', 'old_slug');
     $dates = array('created_on', 'modified_on', 'featured_on', 'published_on');
     $strings = array('title', 'summary', 'description');
     $bools = array('featured');
     list($data, $public_fields) = $this->prepare_for_output($options, $exclude, $bools, $dates, $strings);
     if (!$options['auth'] && $data['visibility'] < 1) {
         unset($data['internal_id']);
     }
     if (!$data['featured']) {
         unset($data['featured_on']);
     }
     $sort = array();
     list($sort['by'], $sort['direction']) = explode(' ', $data['sort']);
     $data['sort'] = $sort;
     $data['__koken__'] = 'album';
     if (array_key_exists('album_type', $data)) {
         switch ($data['album_type']) {
             case 2:
                 $data['album_type'] = 'set';
                 break;
             case 1:
                 $data['album_type'] = 'smart';
                 break;
             default:
                 $data['album_type'] = 'standard';
         }
     }
     if ($this->album_type == 2) {
         $sum = new Album();
         $sum->select_sum('total_count')->select_sum('video_count')->where('right_id <', $this->right_id)->where('left_id >', $this->left_id)->where('album_type', 0)->where('visibility', 0)->get();
         $data['counts'] = array('total' => (int) $this->total_count, 'videos' => (int) $sum->video_count, 'images' => $sum->total_count - $sum->video_count);
     } else {
         $data['counts'] = array('total' => (int) $this->total_count, 'videos' => (int) $this->video_count, 'images' => $this->total_count - $this->video_count);
     }
     $data['tags'] = $this->_get_tags_for_output($options);
     $data['categories'] = array('count' => is_null($this->category_count) ? $this->categories->count() : (int) $this->category_count, 'url' => $koken_url_info->base . 'api.php?/albums/' . $data['id'] . '/categories');
     $data['topics'] = array('count' => is_null($this->text_count) ? $this->text->count() : (int) $this->text_count, 'url' => $koken_url_info->base . 'api.php?/albums/' . $data['id'] . '/topics');
     if ($options['with_covers']) {
         $data['covers'] = $existing = array();
         $covers = $this->covers;
         if (isset($options['before'])) {
             $covers->where('published_on <=', $options['before']);
             $data['__cover_hint_before'] = $options['before'];
         }
         $covers->include_related_count('albums', NULL, array('visibility' => 0));
         $covers->include_related_count('categories');
         foreach ($covers->order_by("covers_{$this->db_join_prefix}albums_covers.id ASC")->get_iterated() as $f) {
             if ($f->exists()) {
                 $data['covers'][] = $f->to_array(array('in_album' => $this));
                 $existing[] = $f->id;
             }
         }
         $covers_count_set = false;
         if ($this->album_type == 2) {
             $covers_count_set = $this->covers->count();
         }
         if ($covers_count_set !== false && $covers_count_set < 3) {
             $a = new Album();
             $ids = $a->select('id')->where('right_id <', $this->right_id)->where('left_id >', $this->left_id)->where('visibility', $this->visibility)->get_iterated();
             $id_arr = array();
             foreach ($ids as $id) {
                 $id_arr[] = $id->id;
             }
             if (!empty($id_arr)) {
                 $c = new Content();
                 $q = "SELECT DISTINCT cover_id FROM {$this->db_join_prefix}albums_covers WHERE album_id IN (" . join(',', $id_arr) . ")";
                 if (!empty($existing)) {
                     $q .= ' AND cover_id NOT IN(' . join(',', $existing) . ')';
                 }
                 $covers = $c->query($q . "GROUP BY album_id LIMIT " . (3 - $covers_count_set));
                 $f_ids = array();
                 foreach ($covers as $f) {
                     $f_ids[] = $f->cover_id;
                 }
                 if (!empty($f_ids)) {
                     $c->where_in('id', $f_ids)->get_iterated();
                     foreach ($c as $content) {
                         // TODO: auth needs to be passed in here
                         array_unshift($data['covers'], $content->to_array(array('in_album' => $this)));
                     }
                 }
             }
         }
         // Latest covers first
         $data['covers'] = array_reverse($data['covers']);
     }
     if (isset($options['order_by']) && in_array($options['order_by'], array('created_on', 'modified_on'))) {
         $data['date'] =& $data[$options['order_by']];
     } else {
         $data['date'] =& $data['published_on'];
     }
     if ($data['level'] > 1 && (!array_key_exists('include_parent', $options) || $options['include_parent'])) {
         $parent = new Album();
         $parent->where('left_id <', $data['left_id'])->where('level <', $data['level'])->where('visibility', $this->visibility)->where('deleted', 0)->order_by('left_id DESC')->limit(1)->get();
         $data['parent'] = $parent->to_array();
     } else {
         if ($data['level'] == 1) {
             $data['parent'] = false;
         }
     }
     $cat = isset($options['category']) ? $options['category'] : (isset($options['context']) && strpos($options['context'], 'category-') === 0 ? str_replace('category-', '', $options['context']) : false);
     if ($cat) {
         if (is_numeric($cat)) {
             foreach ($this->categories->get_iterated() as $c) {
                 if ($c->id == $cat) {
                     $cat = $c->slug;
                     break;
                 }
             }
         }
     }
     $data['url'] = $this->url(array('date' => $data['published_on'], 'tag' => isset($options['tags']) ? $options['tags'] : (isset($options['context']) && strpos($options['context'], 'tag-') === 0 ? str_replace('tag-', '', $options['context']) : false), 'category' => $cat));
     if ($data['url']) {
         list($data['__koken_url'], $data['url']) = $data['url'];
         $data['canonical_url'] = $data['url'];
     }
     if (!$options['auth'] && $data['visibility'] > 0) {
         unset($data['url']);
     }
     if (array_key_exists('visibility', $data)) {
         switch ($data['visibility']) {
             case 1:
                 $raw = 'unlisted';
                 break;
             case 2:
                 $raw = 'private';
                 break;
             default:
                 $raw = 'public';
                 break;
         }
         $data['visibility'] = array('raw' => $raw, 'clean' => ucwords($raw));
         $data['public'] = $raw === 'public';
     }
     return Shutter::filter('api.album', array($data, $this, $options));
 }