function purge_trash() { _log("Purging trash..."); $count = Trash::purge_trash(); _log("{$count} objects deleted."); }
/** * Clears old objects in trash according to config option days_on_trash * */ function purge_trash() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } ajx_current("empty"); try { $deleted = Trash::purge_trash(); flash_success("success purging trash", $deleted); } catch (Exception $e) { flash_error($e->getMessage()); } }
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); }
<?php //Check and get the request... (Either 'delete' of 'mark_as_read') if (isset($_REQUEST['action']) && isset($_REQUEST['page'])) { $action = $_REQUEST['action']; $page = $_REQUEST['page']; } else { redirect_to('../extra-404'); } ?> <?php //Process the 'action'... if ($action != 'send') { $selected_message_ids = $_REQUEST['checkboxes']; } $trash_message = new Trash(); if ($action == 'delete') { //Inbox -> delete... if ($page == 'inbox') { foreach ($selected_message_ids as $message_id) { $message_to_delete = Receiver::find_by_user_msg($_SESSION['user_id'], $message_id); //echo ".".$trash_message->user_id . "."; $trash_message->user_id = $message_to_delete->user_id; $trash_message->message_id = $message_to_delete->message_id; $trash_message->type = $page; $trash_message->create(); //Delete message from INBOX now... $message_to_delete->delete(); } } else { if ($page == 'sent') {
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); }
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); }
$user = User::find_by_id($_SESSION['user_id']); //1.the current page number ($current_page) $page = !empty($_GET['page']) ? (int) $_GET['page'] : 1; //2. records per page ($per_page) $per_page = 2; //3.total record count ($total_count) global $database; $sql = "select COUNT(*) FROM trash where user_id=" . $user->id; $result = $database->execute_query($sql); $row = $database->fetch_array($result); $total_count = array_shift($row); $pagination = new Pagination($page, $per_page, $total_count); $sql = "select * from trash where user_id=" . $user->id; $sql .= " LIMIT {$per_page} "; $sql .= "OFFSET {$pagination->offset()}"; $trash_message_ids = Trash::find_by_sql($sql); ?> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Neon Admin Panel" /> <meta name="author" content="" /> <title>LLSCT | Mailbox | Trash</title> <link rel="stylesheet" href="../assets/js/jquery-ui/css/no-theme/jquery-ui-1.10.3.custom.min.css">
if (RedBean_OODB::getVersionNumber()) { SmartTest::instance()->progress(); } else { SmartTest::failedTest(); } SmartTest::instance()->progress(); } catch (Exception $e) { SmartTest::failedTest(); } //Test description: Test redbean table-space SmartTest::instance()->testPack = "Configuration tester"; //insert garbage tables $db->exec(" CREATE TABLE `nonsense` (\n\t\t\t`a` VARCHAR( 11 ) NOT NULL ,\n\t\t\t`b` VARCHAR( 11 ) NOT NULL ,\n\t\t\t`j` VARCHAR( 11 ) NOT NULL\n\t\t\t) ENGINE = MYISAM "); Redbean_OODB::clean(); Redbean_OODB::gen("trash"); $trash = new Trash(); $trash->save(); Redbean_OODB::clean(); Redbean_OODB::setLocking(false); //turn locking off $alltables = $db->getCol("show tables"); SmartTest::instance()->progress(); if (!in_array("dtyp", $alltables)) { SmartTest::failedTest(); } SmartTest::instance()->progress(); if (!in_array("redbeantables", $alltables)) { SmartTest::failedTest(); } SmartTest::instance()->progress(); if (!in_array("locking", $alltables)) {
private function processListActions() { $linkedObject = null; if (array_var($_GET, 'action') == 'delete') { $ids = explode(',', array_var($_GET, 'objects')); $result = ContentDataObjects::listing(array("extra_conditions" => " AND o.id IN (" . implode(",", $ids) . ") ", "include_deleted" => true)); $objects = $result->objects; foreach ($objects as $object) { $object->setDontMakeCalculations(true); } $real_deleted_ids = array(); list($succ, $err) = $this->do_delete_objects($objects, false, $real_deleted_ids); if ($err > 0) { flash_error(lang('error delete objects', $err)); } else { Hook::fire('after_object_delete_permanently', $real_deleted_ids, $ignored); flash_success(lang('success delete objects', $succ)); } } else { if (array_var($_GET, 'action') == 'delete_permanently') { $ids = explode(',', array_var($_GET, 'objects')); $objects = Objects::instance()->findAll(array("conditions" => "id IN (" . implode(",", $ids) . ")")); $real_deleted_ids = array(); list($succ, $err) = $this->do_delete_objects($objects, true, $real_deleted_ids); if ($err > 0) { flash_error(lang('error delete objects', $err)); } if ($succ > 0) { Hook::fire('after_object_delete_permanently', $real_deleted_ids, $ignored); flash_success(lang('success delete objects', $succ)); } } else { if (array_var($_GET, 'action') == 'markasread') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, true); } else { if (array_var($_GET, 'action') == 'markasunread') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, false); } else { if (array_var($_GET, 'action') == 'empty_trash_can') { $result = ContentDataObjects::listing(array("select_columns" => array('id'), "raw_data" => true, "trashed" => true)); $objects = $result->objects; foreach ($objects as $object) { $object->setDontMakeCalculations(true); } if (count($objects) > 0) { $obj_ids_str = implode(',', array_flat($objects)); $extra_conds = "AND o.id IN ({$obj_ids_str})"; $count = Trash::purge_trash(0, 1000, $extra_conds); flash_success(lang('success delete objects', $count)); } } else { if (array_var($_GET, 'action') == 'archive') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'archive'); if ($err > 0) { flash_error(lang('error archive objects', $err)); } else { flash_success(lang('success archive objects', $succ)); } } else { if (array_var($_GET, 'action') == 'unarchive') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'unarchive'); if ($err > 0) { flash_error(lang('error unarchive objects', $err)); } else { flash_success(lang('success unarchive objects', $succ)); } } else { if (array_var($_GET, 'action') == 'unclassify') { $ids = explode(',', array_var($_GET, 'objects')); $err = 0; $succ = 0; foreach ($ids as $id) { $split = explode(":", $id); $type = $split[0]; if (Plugins::instance()->isActivePlugin('mail') && $type == 'MailContents') { $email = MailContents::findById($split[1]); if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) { if (MailController::do_unclassify($email)) { $succ++; } else { $err++; } } else { $err++; } } } if ($err > 0) { flash_error(lang('error unclassify emails', $err)); } else { flash_success(lang('success unclassify emails', $succ)); } } else { if (array_var($_GET, 'action') == 'restore') { $errorMessage = null; $ids = explode(',', array_var($_GET, 'objects')); $success = 0; $error = 0; foreach ($ids as $id) { $obj = Objects::findObject($id); $obj->setDontMakeCalculations(true); if ($obj->canDelete(logged_user())) { try { $obj->untrash($errorMessage); if ($obj->getObjectTypeId() == 11) { $event = ProjectEvents::findById($obj->getId()); if ($event->getExtCalId() != "") { $this->created_event_google_calendar($obj, $event); } } ApplicationLogs::createLog($obj, ApplicationLogs::ACTION_UNTRASH); $success++; } catch (Exception $e) { $error++; } } else { $error++; } } if ($success > 0) { flash_success(lang("success untrash objects", $success)); } if ($error > 0) { $errorString = is_null($errorMessage) ? lang("error untrash objects", $error) : $errorMessage; flash_error($errorString); } } } } } } } } } } if (!array_var($_GET, 'only_result')) { $ignored = null; Hook::fire('after_multi_object_action', array('object_ids' => explode(',', array_var($_GET, 'objects')), 'action' => array_var($_GET, 'action')), $ignored); } }
/** * move 执行入口 * @param bool $isPath - Use path to move if true ,or use id. */ public function invoke($isPath = true) { // 初始化入口 $device = new UserDevice(); $device = $device->findByUserIdAndType($this->_userId, CConst::DEVICE_WEB); $this->_deviceId = $device["id"]; $this->_deviceName = $device["user_device_name"]; $user = User::model()->findByPk($this->_userId); $this->_userNick = $user["user_name"]; $this->master = $this->_userId; // // 空间检查 // $this->handleSpace(); if ($isPath) { $this->fromPath = CUtils::convertStandardPath($this->fromPath); $this->toPath = CUtils::convertStandardPath($this->toPath); $this->initByPath(); } else { $this->initById(); } // // 判断是否是共享 // $from_share_filter = MSharesFilter::init(); $from_share_filter->handlerCheckByFile($this->_userId, $this->from); $this->rename = false; if ($from_share_filter->_is_shared_path && $this->toParent['id'] == 0) { $this->rename = true; } elseif ($from_share_filter->is_shared) { $this->master = $from_share_filter->master; $this->fromPath = '/' . $this->master . $from_share_filter->_path; $this->from = UserFile::model()->findByAttributes(array('is_deleted' => 0, 'file_path' => $this->fromPath)); if (!$this->from) { throw new ApiException("Not found"); } } // // 检查移动原路径与目标路径是否一致,一致则返回成功 // if ($this->fromPath === $this->toPath) { $this->handleResult(false, 0, "已存在同名的文件"); return; } // // 检查是否移动到其子目录下 // if (strpos($this->toPath, $this->fromPath . "/") === 0) { $this->result["msg"] = "不能移动到子目录"; return; } if ($this->toPath == "/{$this->_userId}" || $this->toPath == "/{$this->_userId}/") { $this->result["msg"] = "目标目录不存在"; return; } // // 命名检查 // if (CUtils::checkNameInvalid($this->toPath) != 0 || CUtils::checkNameInvalid($this->toPath) != 0) { $this->result["msg"] = "命名不能包含下列字符串: ^|?*\\<\":>"; return; } // // 存在同名的则,拒绝 // $target = UserFile::model()->findByAttributes(array("user_id" => $this->_userId, "file_path" => $this->toPath, "is_deleted" => 0)); if ($target) { $this->handleResult(false, 0, "已存在同名的文件"); return; } $index = strlen("/{$this->from['user_id']}"); $fpath = substr_replace($this->fromPath, "", 0, $index); $index = strlen("/{$this->toParent['user_id']}"); $tpath = substr_replace($this->toPath, "", 0, $index); // // 检查移动方式 // if ($isPath == false && $this->rename == false && ($from_share_filter->handlerCheckMove($from_share_filter->master, $this->to_share_filter->master, $fpath, $tpath) || $this->to_share_filter->is_shared)) { // // 先copy再删除,如果是移动共享文件夹则只copy,再执行shareManager取消共享 // $copy = new Copy(); $copy->_userId = $this->_userId; $copy->toId = $this->toParent['id']; $copy->fromId = $this->from['id']; try { $copy->invoke(false); } catch (Exception $e) { $this->result["msg"] = "操作失败"; return; } if ($this->from['file_type'] == 2 && $this->from['user_id'] != $this->to_share_filter->operator) { $file_meta = FileMeta::model()->findByAttributes(array('meta_key' => 'shared_folders', 'file_path' => $this->from['file_path'])); if (!$file_meta) { $this->result["msg"] = "操作失败"; return; } $meta_value = unserialize($file_meta['meta_value']); $slaves = $meta_value['slaves']; $this->from = UserFile::model()->findByAttributes(array('file_path' => $slaves[$this->to_share_filter->operator], 'is_deleted' => 0)); if (!$this->from) { $this->result["msg"] = "操作失败"; return; } } $del = new Delete(); $del->_userId = $this->from['user_id']; try { $del->invoke($this->from['id']); $trash = new Trash(); $trash->_userId = $this->master; $trash->fromIds = $this->from['id']; $trash->invoke(Trash::DELETE); } catch (Exception $e) { $this->result["msg"] = "操作失败"; return; } if ($copy->result['state'] && $del->result['state']) { $this->handleResult(true, 0, "操作成功"); $this->result["data"][$this->fromId]["state"] = true; } return; } // 文件直接进行移动 if ($this->from["file_type"] == 0) { $this->handleMoveFile($this->fromPath, $this->toPath); } else { // 文件夹涉及子对象 $this->handleMoveFolder($this->fromPath, $this->toPath); } $this->handleResult(true, 0, "操作成功"); $this->result["data"][$this->fromId]["state"] = true; }
/** * 控制器执行主逻辑函数, 处理删除文件或者文件夹 */ public function invoke($uri = null) { $this->setAction(MConst::DELETE); // 调用父类初始化函数,注册自定义的异常和错误处理逻辑 parent::init(); $params = $_REQUEST; // 检查参数 if (isset($params) === false) { throw new MFileopsException(Yii::t('api', 'Bad Request 8'), MConst::HTTP_CODE_400); } // // 获取用户数据,如user_id $user = MUserManager::getInstance()->getCurrentUser(); $device = MUserManager::getInstance()->getCurrentDevice(); $this->_user_id = $user["user_id"]; $user_nick = $user["user_name"]; $user_device_id = $device["device_id"]; $this->_user_device_name = $device["user_device_name"]; // 文件大小格式化参数 $locale = "bytes"; if (isset($params["locale"])) { $locale = $params["locale"]; } if (isset($params["root"]) === false || isset($params["path"]) === false) { throw new MFileopsException(Yii::t('api', 'Bad Request 9'), MConst::HTTP_CODE_400); } $root = $params["root"]; $path = $params["path"]; $isDir = $params["is_dir"]; $pathArr = explode('/', $path); if ($path == '/' || empty($pathArr[2]) || empty($pathArr[1])) { return; } if ($isDir) { //避免人为添加删除目录 $arr = explode('/', $path); $isRoot = false; $isMine = false; if (count($arr) == 3) { $isRoot = true; } $fileOwnerId = $arr[1]; $currentUserId = $this->_user_id; if ($fileOwnerId == $currentUserId) { $isMine = true; } if ($isRoot && !$isMine) { //如果是在根目录下且不是自己的目录 则后台控制不准取消共享 throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_409); } } // // 转换路径分隔符,便于以后跨平台,如:将 "\"=>"/" // $path = MUtils::convertStandardPath($path); if ($path == "" || $path == "/" || $path === false) { throw new MFileopsException(Yii::t('api', 'Bad request 10'), MConst::HTTP_CODE_400); } // 检查是否是共享目录 $share_filter = MSharesFilter::init(); if ($share_filter->handlerCheck($this->_user_id, $path)) { $this->_user_id = $share_filter->master; $path = $share_filter->_path; } // // 如果删除的是共享目录,则转到ShareManager处理 // if ($share_filter->_is_shared_path && $share_filter->operator != $share_filter->master) { $file = MFiles::queryFilesByPath("/" . $share_filter->operator . $share_filter->src_path); if (!$file) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } $id = $file[0]["id"]; $handler = new ShareManager(); $handler->_userId = $share_filter->operator; $handler->_id = $id; try { $handler->invoke(ShareManager::CANCEL_SHARED); } catch (Exception $e) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } // 输出返回值 $path = MUtils::convertStandardPath($share_filter->src_path); $this->buildResult($root, $path, $handler->_file["version_id"], $handler->_file["file_update_time"], true); return; } if ($share_filter->_is_shared_path && $share_filter->operator != $share_filter->master) { throw new MException(Yii::t('api', 'You do not have permission to perform the delete operation.'), MConst::HTTP_CODE_409); } // // 组装对象信息 // $file_name = MUtils::get_basename($path); $file_detail = new MFiles(); $file_detail->file_name = $file_name; $file_detail->file_path = $path; // // 查询其目录信息,是否存在 // $query_db_file = MFiles::queryFilesByPath($file_detail->file_path); //数据已不存在 if (count($query_db_file) <= 0) { throw new MFileopsException(Yii::t('api', 'Not found the source files of the specified path'), MConst::HTTP_CODE_404); } $data = array("obj" => $this, "share_filter" => $share_filter, "query_db_file" => $query_db_file[0]); //在共享文件夹中进行删除权限判断 if ($share_filter->is_shared && $query_db_file[0]["file_type"] != MConst::OBJECT_TYPE_BESHARED) { if ($query_db_file[0]["file_type"] == 0) { //文件删除 $share_filter->hasPermissionExecute($query_db_file[0]["file_path"], MPrivilege::FILE_DELETE); } else { //文件夹删除 $share_filter->hasPermissionExecute($query_db_file[0]["file_path"], MPrivilege::FOLDER_DELETE); } } // // 可以删除包含子文件的目录 // 检查其是否为文件夹 // $files = array(); $file_detail->is_dir = false; $file_detail->id = $query_db_file[0]["id"]; $file_detail->file_size = $query_db_file[0]["file_size"]; $file_detail->file_type = $query_db_file[0]["file_type"]; if ($query_db_file[0]["file_type"] > MConst::OBJECT_TYPE_FILE) { $file_detail->is_dir = true; $files = $this->handleChildrenFile($file_detail->file_path, $files); } else { // 处理加入版本历史 $this->handleFileMeta($file_detail->file_path, $query_db_file[0]["version_id"], $this->_user_id, $user_nick, $this->_user_device_name, $file_detail->file_size); } $isSharedPath = false; $pathArr = explode('/', $file_detail->file_path); $masterId = $pathArr[1]; if ($masterId != $this->_user_id) { $isSharedPath = true; } else { $model = new GeneralFolderPermissionBiz($file_detail->file_path); if ($model->isParentShared($file_detail->file_path)) { //如果是父目录被共享 $isSharedPath = true; } } if ($isSharedPath) { $permissionArr = UserPermissionBiz::getInstance()->getPermission($file_detail->file_path, $user["user_id"]); $permission = $permissionArr['permission']; if (!empty($permission)) { $privilegeModel = new PrivilegeBiz(); $share_filter->slaves = $privilegeModel->getSlaveIdsByPath($permissionArr['share_root_path']); $share_filter->is_shared = true; if ($file_detail->file_type == 0) { //删除文件 $can_file_delete = substr($permission, 7, 1); if ($can_file_delete == 0) { throw new MFileopsException(Yii::t('api', 'no permission'), MConst::HTTP_CODE_409); } } if ($file_detail->file_type == 1 || $file_detail->file_type == 2 || $file_detail->file_type == 4) { $can_folder_delete = substr($permission, 3, 1); if ($can_folder_delete == 0) { throw new MFileopsException(Yii::t('api', 'no permission'), MConst::HTTP_CODE_409); } } } } // // 更新文件元数据的为删除数据 // $this->assembleFileDetail($file_detail, $query_db_file[0]); $ret_value = MFiles::updateRemoveFileDetail($file_detail); if ($ret_value === false) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } // // 将删除目录加入数组 // array_push($files, $file_detail); // // 保存事件 // $ret_value = MiniEvent::getInstance()->createEvents($this->_user_id, $user_device_id, $files, $share_filter->type); if ($ret_value === false) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } // // // if ($share_filter->is_shared) { foreach ($files as $file) { $share_filter->handlerAction($file->event_action, $user_device_id, $file->from_path, $file->context); } } // // 删除共享目录(删除共享目录,对应的权限也一起删除) // //首先判断用户有无删除权限 $userPrivilegeList = MiniUserPrivilege::getInstance()->getPrivilegeList($file_detail->file_path); $groupPrivilegeList = MiniGroupPrivilege::getInstance()->getPrivilegeList($file_detail->file_path); if (!empty($userPrivilegeList)) { MiniUserPrivilege::getInstance()->deleteByFilePath($file_detail->file_path); } if (!empty($groupPrivilegeList)) { MiniGroupPrivilege::getInstance()->deleteByFilePath($file_detail->file_path); } //并且将file_type改为1 if ($file_detail->file_type == 0) { MiniFile::getInstance()->togetherShareFile($file_detail->file_path, Mconst::OBJECT_TYPE_FILE); } else { MiniFile::getInstance()->togetherShareFile($file_detail->file_path, Mconst::OBJECT_TYPE_DIRECTORY); } if ($filter !== true && $share_filter->_is_shared_path && $share_filter->operator == $share_filter->master) { $file = MFiles::queryFilesByPath("/" . $share_filter->operator . $path, true); if (!$file) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } $id = $file[0]["id"]; $handler = new ShareManager(); $handler->_userId = $share_filter->operator; $handler->_id = $id; try { $handler->invoke(ShareManager::CANCEL_SHARED); } catch (Exception $e) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } } // 如果彻底删除,则调用回收站 if ($this->completely_remove) { $trash = new Trash(); $trash->_userId = $this->_user_id; $trash->fromIds = $file_detail->id; try { $trash->invoke(Trash::DELETE); } catch (Exception $e) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } //执行的额外操作 $this->extend($share_filter, $query_db_file, $file_detail); return; } $path = CUtils::removeUserFromPath($query_db_file[0]["file_path"]); $path_info = MUtils::pathinfo_utf($path); $path_info_out = MUtils::pathinfo_utf($share_filter->src_path); $path = MUtils::convertStandardPath($path_info_out['dirname'] . "/" . $path_info['basename']); //执行的额外操作 $this->extend($share_filter, $query_db_file, $file_detail); $this->buildResult($root, $path, $query_db_file[0]["version_id"], $query_db_file[0]["file_update_time"], $file_detail->is_dir); }
/** * 创建文件 * @param array $fileDetail * @throws * @return array */ private function createFile($fileDetail) { // // 如果创建文件标志为false,则不执行创建 // if ($this->create_file == false) { return; } // // 是否有标记为删除的对象,可能存在多个 // $conflictFile = MFiles::queryFilesByPath($this->file_path, TRUE); if ($conflictFile != false && empty($conflictFile) == false) { foreach ($conflictFile as $file) { // // 如果非文件类型,删除 // if ($file["file_type"] == MConst::OBJECT_TYPE_FILE) { $fileDetail = MFiles::exchange2Object($file, TRUE); $this->creatFileDeleted($fileDetail); return; } else { // 彻底删除之后再进行创建 $trash = new Trash(); $trash->_userId = $this->user_id; $trash->fromIds = $file['id']; try { $trash->invoke(Trash::DELETE); } catch (Exception $e) { throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_500); } } } } $this->spaceFilter($this->size); // 过滤器,空间大小计算 $fileDetail->file_create_time = $this->file_create_time; $fileDetail->file_update_time = $this->file_update_time; $fileDetail->file_size = $this->size; $fileDetail->file_type = MConst::OBJECT_TYPE_FILE; $fileDetail->parent_file_id = $this->parent_file_id; $fileDetail->version_id = $this->version_id; $fileDetail->file_path = $this->path; $fileDetail->file_name = $this->file_name; $fileDetail->event_uuid = MiniUtil::getEventRandomString(MConst::LEN_EVENT_UUID); $fileDetail->mime_type = $this->type; // // 创建文件时,如果存在老的版本 需要兼容 不能覆盖 // $metaValue = null; $fileMeta = MFileMetas::queryFileMeta($fileDetail->file_path, MConst::VERSION); if ($fileMeta) { $metaValue = $fileMeta[0]['meta_value']; } // // 文件meta属性,版本信息 // $version = MUtils::getFileVersions($this->user_device_name, $fileDetail->file_size, $this->version_id, $this->action, $this->user_id, $this->user_nick, $metaValue); // // 保存文件元数据 // $retVal = MFiles::CreateFileDetail($fileDetail, $this->user_id, $this->user_nick); if ($retVal === false) { throw new MFilesException(Yii::t('api', MConst::INTERNAL_SERVER_ERROR), MConst::HTTP_CODE_500); } // // 保存事件 // $this->context = array("hash" => $this->file_hash, "rev" => (int) $this->version_id, "bytes" => (int) $this->size, "update_time" => (int) $this->file_update_time, "create_time" => (int) $this->file_create_time); $retVal = MiniEvent::getInstance()->createEvent($this->currentUserId, $this->user_device_id, $this->action, $this->file_path, serialize($this->context), $fileDetail->event_uuid, $this->share_filter->type); // 为每个共享用户创建事件 $this->share_filter->handlerAction($this->action, $this->user_device_id, $this->file_path, $this->context); if (isset($fileDetail->event_uuid)) { $this->event_uuid = $fileDetail->event_uuid; } if ($retVal === false) { throw new MFilesException(Yii::t('api', MConst::INTERNAL_SERVER_ERROR), MConst::HTTP_CODE_500); } // 文件版本引用次数更新 if (MiniVersion::getInstance()->updateRefCount($this->version_id) == false) { throw new MFilesException(Yii::t('api', MConst::INTERNAL_SERVER_ERROR), MConst::HTTP_CODE_500); } if ($fileMeta) { $retVal = MFileMetas::updateFileMeta($this->file_path, MConst::VERSION, $version); } else { $retVal = MFileMetas::createFileMeta($this->file_path, MConst::VERSION, $version); $pathArr = explode('/', $this->file_path); $user = Yii::app()->session["user"]; if ((int) $pathArr[1] !== (int) $user['user_id']) { //只有当被共享者在共享目录下创建文件时,才会记录create_id MFileMetas::createFileMeta($this->file_path, 'create_id', $user['user_id']); } } if ($retVal === false) { throw new MFilesException(Yii::t('api', MConst::INTERNAL_SERVER_ERROR), MConst::HTTP_CODE_500); } }