Пример #1
0
 static function get($block_id, $theme)
 {
     $block = "";
     switch ($block_id) {
         case "random_image":
             // The random_query approach is flawed and doesn't always return a
             // result when there actually is one. Retry a *few* times.
             // @todo Consider another fallback if further optimizations are necessary.
             $image_count = module::get_var("image_block", "image_count");
             $items = array();
             for ($i = 0; $i < $image_count; $i++) {
                 $attempts = 0;
                 $item = null;
                 do {
                     $item = item::random_query()->where("type", "!=", "album")->find_all(1)->current();
                 } while (!$item && $attempts++ < 3);
                 if ($item) {
                     $items[] = $item;
                 }
             }
             if ($items) {
                 $block = new Block();
                 $block->css_id = "g-image-block";
                 $block->title = t2("Random image", "Random images", $image_count);
                 $block->content = new View("image_block_block.html");
                 $block->content->items = $items;
             }
             break;
     }
     return $block;
 }
Пример #2
0
    public function delete($ptID = false)
    {
        $pagetype = PageType::getByID($ptID);
        if (!is_object($pagetype)) {
            $this->error->add(t('Invalid page type object.'));
        }
        $cmp = new \Permissions($pagetype);
        if (!$cmp->canDeletePageType()) {
            $this->error->add(t('You do not have access to delete this page type.'));
        }

        $count = $pagetype->getPageTypeUsageCount();
        if ($count > 0) {
            $this->error->add(t2(
                'This page type is in use on %d page.',
                'This page type is in use on %d pages.', $count));
        }

        if (!$this->token->validate('delete_page_type')) {
            $this->error->add(t($this->token->getErrorMessage()));
        }
        if (!$this->error->has()) {
            $pagetype->delete();
            $this->redirect('/dashboard/pages/types', 'page_type_deleted');
        }
        $this->view();
    }
Пример #3
0
    public function rescan() {
        $files = $this->getRequestFiles('canEditFileContents');
        $r = new FileEditResponse();
        $r->setFiles($files);
        $successMessage = '';
        $errorMessage = '';
        $successCount = 0;

        foreach($files as $f) {
            try {
                $fv = $f->getApprovedVersion();
                $resp = $fv->refreshAttributes();
                switch ($resp) {
                    case \Concrete\Core\File\Importer::E_FILE_INVALID:
                        $errorMessage .= t('File %s could not be found.', $fv->getFilename()) . '<br/>';
                        break;
                    default:
                        $successCount++;
                        $successMessage = t2('%s file rescanned successfully.', '%s files rescanned successfully.',
                            $successCount);
                        break;
                }
            } catch(\Concrete\Flysystem\FileNotFoundException $e) {
                $errorMessage .= t('File %s could not be found.', $fv->getFilename()) . '<br/>';
            }
        }
        if ($errorMessage && !$successMessage) {
            $e = new \Concrete\Core\Error\Error;
            $e->add($errorMessage);
            $r->setError($e);
        } else {
            $r->setMessage($errorMessage . $successMessage);
        }
        $r->outputJSON();
    }
Пример #4
0
 public function rescan_locale()
 {
     if ($this->token->validate('rescan_locale')) {
         $u = new \User();
         if ($u->isSuperUser()) {
             \Core::make('cache/request')->disable();
             $section = Section::getByID($_REQUEST['locale']);
             $target = new MultilingualProcessorTarget($section);
             $processor = new Processor($target);
             if ($_POST['process']) {
                 foreach ($processor->receive() as $task) {
                     $processor->execute($task);
                 }
                 $obj = new \stdClass();
                 $obj->totalItems = $processor->getTotalTasks();
                 echo json_encode($obj);
                 exit;
             } else {
                 $processor->process();
             }
             $totalItems = $processor->getTotalTasks();
             \View::element('progress_bar', array('totalItems' => $totalItems, 'totalItemsSummary' => t2("%d task", "%d tasks", $totalItems)));
             exit;
         }
     }
 }
Пример #5
0
 static function update_index($task)
 {
     try {
         $completed = $task->get("completed", 0);
         $start = microtime(true);
         foreach (ORM::factory("item")->join("exif_records", "items.id", "exif_records.item_id", "left")->where("type", "photo")->open_paren()->where("exif_records.item_id", null)->orwhere("exif_records.dirty", 1)->close_paren()->find_all() as $item) {
             if (microtime(true) - $start > 1.5) {
                 break;
             }
             $completed++;
             exif::extract($item);
         }
         list($remaining, $total, $percent) = exif::stats();
         $task->set("completed", $completed);
         if ($remaining == 0 || !($remaining + $completed)) {
             $task->done = true;
             $task->state = "success";
             site_status::clear("exif_index_out_of_date");
             $task->percent_complete = 100;
         } else {
             $task->percent_complete = round(100 * $completed / ($remaining + $completed));
         }
         $task->status = t2("one record updated, index is %percent% up-to-date", "%count records updated, index is %percent% up-to-date", $completed, array("percent" => $percent));
     } catch (Exception $e) {
         $task->done = true;
         $task->state = "error";
         $task->status = $e->getMessage();
         $task->log($e->__toString());
     }
 }
Пример #6
0
 static function fix_internet_addresses($task)
 {
     $start = microtime(true);
     $total = $task->get("total");
     if (empty($total)) {
         $task->set("total", $total = db::build()->count_records("items"));
         $task->set("last_id", 0);
         $task->set("completed", 0);
     }
     $last_id = $task->get("last_id");
     $completed = $task->get("completed");
     foreach (ORM::factory("item")->where("id", ">", $last_id)->find_all(100) as $item) {
         $item->slug = item::convert_filename_to_slug($item->slug);
         $item->save();
         $last_id = $item->id;
         $completed++;
         if ($completed == $total || microtime(true) - $start > 1.5) {
             break;
         }
     }
     $task->set("completed", $completed);
     $task->set("last_id", $last_id);
     if ($total == $completed) {
         $task->done = true;
         $task->state = "success";
         $task->percent_complete = 100;
         db::build()->update("items")->set("relative_path_cache", null)->set("relative_url_cache", null)->execute();
     } else {
         $task->percent_complete = round(100 * $completed / $total);
     }
     $task->status = t2("One row updated", "%count / %total rows updated", $completed, array("total" => $total));
 }
Пример #7
0
 public function run()
 {
     Cache::disableCache();
     Loader::library('database_indexed_search');
     $is = new IndexedSearch();
     if ($_GET['force'] == 1) {
         Loader::model('attribute/categories/collection');
         Loader::model('attribute/categories/file');
         Loader::model('attribute/categories/user');
         $attributes = CollectionAttributeKey::getList();
         $attributes = array_merge($attributes, FileAttributeKey::getList());
         $attributes = array_merge($attributes, UserAttributeKey::getList());
         foreach ($attributes as $ak) {
             $ak->updateSearchIndex();
         }
         $result = $is->reindexAll(true);
     } else {
         $result = $is->reindexAll();
     }
     if ($result->count == 0) {
         return t('Indexing complete. Index is up to date');
     } else {
         if ($result->count == $is->searchBatchSize) {
             return t('Index partially updated. %s pages indexed (maximum number.) Re-run this job to continue this process.', $result->count);
         } else {
             return t('Index updated.') . ' ' . t2('%d page required reindexing.', '%d pages required reindexing.', $result->count, $result->count);
         }
     }
 }
Пример #8
0
 static function update_index($task)
 {
     try {
         $completed = $task->get("completed", 0);
         $start = microtime(true);
         foreach (ORM::factory("item")->join("exif_records", "items.id", "exif_records.item_id", "left")->where("type", "=", "photo")->and_open()->where("exif_records.item_id", "IS", null)->or_where("exif_records.dirty", "=", 1)->close()->find_all() as $item) {
             // The query above can take a long time, so start the timer after its done
             // to give ourselves a little time to actually process rows.
             if (!isset($start)) {
                 $start = microtime(true);
             }
             exif::extract($item);
             $completed++;
             if (microtime(true) - $start > 1.5) {
                 break;
             }
         }
         list($remaining, $total, $percent) = exif::stats();
         $task->set("completed", $completed);
         if ($remaining == 0 || !($remaining + $completed)) {
             $task->done = true;
             $task->state = "success";
             site_status::clear("exif_index_out_of_date");
             $task->percent_complete = 100;
         } else {
             $task->percent_complete = round(100 * $completed / ($remaining + $completed));
         }
         $task->status = t2("one record updated, index is %percent% up-to-date", "%count records updated, index is %percent% up-to-date", $completed, array("percent" => $percent));
     } catch (Exception $e) {
         $task->done = true;
         $task->state = "error";
         $task->status = $e->getMessage();
         $task->log((string) $e);
     }
 }
Пример #9
0
 /**
  * Task that rebuilds all dirty images.
  * @param Task_Model the task
  */
 static function rebuild_dirty_images($task)
 {
     $result = graphics::find_dirty_images_query();
     $remaining = $result->count();
     $completed = $task->get("completed", 0);
     $i = 0;
     foreach ($result as $row) {
         $item = ORM::factory("item", $row->id);
         if ($item->loaded) {
             graphics::generate($item);
         }
         $completed++;
         $remaining--;
         if (++$i == 2) {
             break;
         }
     }
     $task->status = t2("Updated: 1 image. Total: %total_count.", "Updated: %count images. Total: %total_count.", $completed, array("total_count" => $remaining + $completed));
     if ($completed + $remaining > 0) {
         $task->percent_complete = (int) (100 * $completed / ($completed + $remaining));
     } else {
         $task->percent_complete = 100;
     }
     $task->set("completed", $completed);
     if ($remaining == 0) {
         $task->done = true;
         $task->state = "success";
         site_status::clear("graphics_dirty");
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $db = \Database::connection();
     $em = $db->getEntityManager();
     $cacheDriver = $em->getConfiguration()->getMetadataCacheImpl();
     $cacheDriver->flushAll();
     $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
     $schemas = [];
     /**
      * @var $sm MySqlSchemaManager
      */
     $sm = $db->getSchemaManager();
     $dbSchema = $sm->createSchema();
     // core xml tables
     $schemas[] = Schema::getCoreXMLSchema();
     // core entities
     $sm = new DatabaseStructureManager($em);
     $entities = $sm->getMetadatas();
     $schemas[] = $tool->getSchemaFromMetadata($entities);
     // core, application and package block types
     $env = Environment::get();
     $list = new BlockTypeList();
     $list->includeInternalBlockTypes();
     foreach ($list->get() as $bt) {
         $r = $env->getRecord(DIRNAME_BLOCKS . '/' . $bt->getBlockTypeHandle() . '/' . FILENAME_BLOCK_DB, $bt->getPackageHandle());
         if ($r->exists()) {
             $parser = Schema::getSchemaParser(simplexml_load_file($r->file));
             $parser->setIgnoreExistingTables(false);
             $schemas[] = $parser->parse($db);
         }
     }
     // packages
     $packages = Package::getInstalledList();
     foreach ($packages as $pkg) {
         $xmlFile = $pkg->getPackagePath() . '/' . FILENAME_BLOCK_DB;
         if (file_exists($xmlFile)) {
             $parser = Schema::getSchemaParser(simplexml_load_file($xmlFile));
             $parser->setIgnoreExistingTables(false);
             $schemas[] = $parser->parse($db);
         }
     }
     // Finalize output.
     $comparator = new \Doctrine\DBAL\Schema\Comparator();
     $saveQueries = array();
     foreach ($schemas as $schema) {
         $schemaDiff = $comparator->compare($dbSchema, $schema);
         $saveQueries = array_merge($saveQueries, $schemaDiff->toSaveSql($db->getDatabasePlatform()));
     }
     $saveQueries = $this->filterQueries($saveQueries);
     if (count($saveQueries)) {
         $output->writeln(t2('%s query found', '%s queries found', count($saveQueries)));
         $i = 1;
         foreach ($saveQueries as $query) {
             $output->writeln(sprintf('%s: %s', $i, $query));
             $i++;
         }
     } else {
         $output->writeln(t('No differences found between schema and database.'));
     }
 }
Пример #11
0
 public function run()
 {
     $cfg = new Config();
     $pNum = (int) $cfg->get('OLD_VERSION_JOB_PAGE_NUM');
     $pNum = $pNum < 0 ? 1 : $pNum + 1;
     $pl = new PageList();
     $pl->setItemsPerPage(3);
     /* probably want to keep a record of pages that have been gone through 
      * so you don't start from the beginning each time..
      */
     $pages = $pl->getPage($pNum);
     if (!count($pages)) {
         $cfg->save('OLD_VERSION_JOB_PAGE_NUM', 0);
         return t("All pages have been processed, starting from beginning on next run.");
     }
     $versionCount = 0;
     $pagesAffected = array();
     foreach ($pages as $page) {
         if ($page instanceof Page) {
             $pvl = new VersionList($page);
             $pagesAffected[] = $page->getCollectionID();
             foreach (array_slice(array_reverse($pvl->getVersionListArray()), 10) as $v) {
                 if ($v instanceof CollectionVersion && !$v->isApproved() && !$v->isMostRecent()) {
                     @$v->delete();
                     $versionCount++;
                 }
             }
         }
     }
     $pageCount = count($pagesAffected);
     $cfg->save('OLD_VERSION_JOB_PAGE_NUM', $pNum);
     //i18n: %1$d is the number of versions deleted, %2$d is the number of affected pages, %3$d is the number of times that the Remove Old Page Versions job has been executed.
     return t2('%1$d versions deleted from %2$d page (%3$d)', '%1$d versions deleted from %2$d pages (%3$s)', $pageCount, $versionCount, $pageCount, implode(',', $pagesAffected));
 }
Пример #12
0
 static function available_tasks()
 {
     $q = emboss::find_dirty();
     $n = $q->count();
     $description = $n == 0 ? t('All photo overlays are up to date') : t2('one Photo needs its emboss overlay updated', "{$n} Photos need their emboss overlay updated", $n);
     $tasks[] = Task_Definition::factory()->callback('emboss_task::update_overlays')->name(t('Update photo embossing'))->description($description)->severity($n > 0 ? log::WARNING : log::SUCCESS);
     return $tasks;
 }
Пример #13
0
 /**
  * Fix up tag counts and delete any tags that have no associated items.
  * @param Task_Model the task
  */
 static function clean_up_tags($task)
 {
     $errors = array();
     try {
         $start = microtime(true);
         $last_tag_id = $task->get("last_tag_id", null);
         $current = 0;
         $total = 0;
         switch ($task->get("mode", "init")) {
             case "init":
                 $task->set("total", ORM::factory("tag")->count_all());
                 $task->set("mode", "clean_up_tags");
                 $task->set("completed", 0);
                 $task->set("last_tag_id", 0);
             case "clean_up_tags":
                 $completed = $task->get("completed");
                 $total = $task->get("total");
                 $last_tag_id = $task->get("last_tag_id");
                 $tags = ORM::factory("tag")->where("id", ">", $last_tag_id)->find_all(25);
                 Kohana_Log::add("error", print_r(Database::instance()->last_query(), 1));
                 while ($current < $total && microtime(true) - $start < 1 && ($tag = $tags->current())) {
                     $last_tag_id = $tag->id;
                     $real_count = $tag->items_count();
                     if ($tag->count != $real_count) {
                         $tag->count = $real_count;
                         if ($tag->count) {
                             $task->log("Fixing count for tag {$tag->name} (id: {$tag->id}, new count: {$tag->count})");
                             $tag->save();
                         } else {
                             $task->log("Deleting empty tag {$tag->name} ({$tag->id})");
                             $tag->delete();
                         }
                     }
                     $completed++;
                     $tags->next();
                 }
                 $task->percent_complete = $completed / $total * 100;
                 $task->set("completed", $completed);
                 $task->set("last_tag_id", $last_tag_id);
         }
         $task->status = t2("Examined %count tag", "Examined %count tags", $completed);
         if ($completed == $total) {
             $task->done = true;
             $task->state = "success";
             $task->percent_complete = 100;
         }
     } catch (Exception $e) {
         Kohana_Log::add("error", (string) $e);
         $task->done = true;
         $task->state = "error";
         $task->status = $e->getMessage();
         $errors[] = (string) $e;
     }
     if ($errors) {
         $task->log($errors);
     }
 }
Пример #14
0
 public function status($success_count, $error_count)
 {
     if ($error_count) {
         // The "errors" won't be properly pluralized :-/
         print t2("Uploaded %count photo (%error errors)", "Uploaded %count photos (%error errors)", (int) $success_count, array("error" => (int) $error_count));
     } else {
         print t2("Uploaded %count photo", "Uploaded %count photos", $success_count);
     }
 }
Пример #15
0
 public function rescan_locale()
 {
     if ($this->token->validate('rescan_locale')) {
         $u = new \User();
         if ($u->isSuperUser()) {
             \Core::make('cache/request')->disable();
             $section = Section::getByID($_REQUEST['locale']);
             $target = new MultilingualProcessorTarget($section);
             $processor = new Processor($target);
             if ($_POST['process']) {
                 foreach ($processor->receive() as $task) {
                     $processor->execute($task);
                 }
                 $obj = new \stdClass();
                 $obj->totalItems = $processor->getTotalTasks();
                 print json_encode($obj);
                 exit;
             } else {
                 $processor->process();
             }
             $totalItems = $processor->getTotalTasks();
             \View::element('progress_bar', array('totalItems' => $totalItems, 'totalItemsSummary' => t2("%d task", "%d tasks", $totalItems)));
             /*
             $q = Queue::get('rescan_multilingual_section');
             if ($_POST['process']) {
                 $obj = new \stdClass;
                 $messages = $q->receive(\Config::get('concrete.limits.copy_pages'));
                 foreach($messages as $key => $p) {
                     // delete the page here
                     $page = unserialize($p->body);
                     $oc = \Page::getByID($page['cID']);
             
             
                     $q->deleteMessage($p);
                 }
             
                 $obj->totalItems = $q->count();
                 print json_encode($obj);
                 if ($q->count() == 0) {
                     $q->deleteQueue('rescan_multilingual_section');
                 }
                 exit;
             
             } else if ($q->count() == 0) {
                 $oc = Section::getByID($_REQUEST['locale']);
                 if (is_object($oc) && !$oc->isError()) {
                     $oc->queueForDeletionRequest($q, false);
                 }
             }
             $totalItems = $q->count();
             \View::element('progress_bar', array('totalItems' => $totalItems, 'totalItemsSummary' => t2("%d page", "%d pages", $totalItems)));
             */
             exit;
         }
     }
 }
Пример #16
0
 private function _get_base_view()
 {
     $view = new Admin_View("admin.html");
     $view->content = new View("admin_comments.html");
     $view->content->published = $this->_query(array("published"));
     $view->content->unpublished = $this->_query(array("unpublished"));
     $view->content->spam = $this->_query(array("spam"));
     $view->content->deleted = $this->_query(array("deleted"));
     $view->content->menu = Menu::factory("root")->append(Menu::factory("link")->id("unpublished")->label(t2("Awaiting Moderation (%count)", "Awaiting Moderation (%count)", $view->content->unpublished->count()))->url(url::site("admin/comments/queue/unpublished")))->append(Menu::factory("link")->id("published")->label(t2("Approved (%count)", "Approved (%count)", $view->content->published->count()))->url(url::site("admin/comments/queue/published")))->append(Menu::factory("link")->id("spam")->label(t2("Spam (%count)", "Spam (%count)", $view->content->spam->count()))->url(url::site("admin/comments/queue/spam")))->append(Menu::factory("link")->id("deleted")->label(t2("Recently Deleted (%count)", "Recently Deleted (%count)", $view->content->deleted->count()))->url(url::site("admin/comments/queue/deleted")));
     return $view;
 }
 public function run()
 {
     $pl = new PageList();
     $pl->filterByCollectionTypeHandle('walk');
     $pl->filterByName('', true);
     $pages = $pl->get();
     $pagecount = count($pages);
     foreach ($pages as $page) {
         $page->moveToTrash();
     }
     return $pagecount . ' ' . t2('page', 'pages', $pagecount) . ' moved to the trash';
 }
Пример #18
0
 /**
  * Show a list of all available, running and finished tasks.
  */
 public function index()
 {
     $query = db::build()->update("tasks")->set("state", "stalled")->where("done", "=", 0)->where("state", "<>", "stalled")->where(new Database_Expression("UNIX_TIMESTAMP(NOW()) - `updated` > 15"))->execute();
     $stalled_count = $query->count();
     if ($stalled_count) {
         log::warning("tasks", t2("One task is stalled", "%count tasks are stalled", $stalled_count), t('<a href="%url">view</a>', array("url" => html::mark_clean(url::site("admin/maintenance")))));
     }
     $view = new Admin_View("admin.html");
     $view->content = new View("admin_maintenance.html");
     $view->content->task_definitions = task::get_definitions();
     $view->content->running_tasks = ORM::factory("task")->where("done", "=", 0)->order_by("updated", "DESC")->find_all();
     $view->content->finished_tasks = ORM::factory("task")->where("done", "=", 1)->order_by("updated", "DESC")->find_all();
     print $view;
 }
Пример #19
0
 /**
  * Show a list of all available, running and finished tasks.
  */
 public function index()
 {
     $query = Database::instance()->query("UPDATE {tasks} SET `state` = 'stalled' " . "WHERE done = 0 " . "AND   state <> 'stalled' " . "AND   unix_timestamp(now()) - updated > 15");
     $stalled_count = $query->count();
     if ($stalled_count) {
         log::warning("tasks", t2("One task is stalled", "%count tasks are stalled", $stalled_count), t('<a href="%url">view</a>', array("url" => html::mark_clean(url::site("admin/maintenance")))));
     }
     $view = new Admin_View("admin.html");
     $view->content = new View("admin_maintenance.html");
     $view->content->task_definitions = task::get_definitions();
     $view->content->running_tasks = ORM::factory("task")->where("done", 0)->orderby("updated", "DESC")->find_all();
     $view->content->finished_tasks = ORM::factory("task")->where("done", 1)->orderby("updated", "DESC")->find_all();
     print $view;
 }
Пример #20
0
 /**
  * Show a list of all available, running and finished tasks.
  */
 public function index()
 {
     $query = Database::instance()->query("UPDATE `tasks` SET `state` = 'stalled' " . "WHERE done = 0 " . "AND   state <> 'stalled' " . "AND   unix_timestamp(now()) - updated > 120");
     $stalled_count = $query->count();
     if ($stalled_count) {
         log::warning("tasks", t2("One task is stalled", "%count tasks are stalled", $stalled_count), t("%link_startview%link_end", array("link_start" => "<a href=\"" . url::site("admin/maintenance") . "\">", "link_start" => "</a>")));
     }
     $view = new Admin_View("admin.html");
     $view->content = new View("admin_maintenance.html");
     $view->content->task_definitions = $this->_get_task_definitions();
     $view->content->running_tasks = ORM::factory("task")->where("done", 0)->orderby("updated", "desc")->find_all();
     $view->content->finished_tasks = ORM::factory("task")->where("done", 1)->orderby("updated", "desc")->find_all();
     $view->content->csrf = access::csrf_token();
     print $view;
 }
Пример #21
0
 /**
  * @param Task_Model the task
  */
 static function set_auto_date_all($task)
 {
     $errors = array();
     try {
         $start = microtime(true);
         $last_item_id = $task->get("last_item_id", null);
         $current = 0;
         $total = 0;
         switch ($task->get("mode", "init")) {
             case "init":
                 $task->set("total", ORM::factory("item")->where("type", "!=", "album")->and_where("captured", "is", NULL)->count_all());
                 $task->set("mode", "set_auto_date_all");
                 $task->set("completed", 0);
                 $task->set("last_item_id", 0);
             case "set_auto_date_all":
                 $completed = $task->get("completed");
                 $total = $task->get("total");
                 $last_item_id = $task->get("last_item_id");
                 $items = ORM::factory("item")->where("id", ">", $last_item_id)->and_where("type", "!=", "album")->and_where("captured", "is", NULL)->find_all(100);
                 /* TODO: should we fetch more at a time? Less? */
                 while ($current < $total && microtime(true) - $start < 1 && ($item = $items->current())) {
                     $last_tem_id = $item->id;
                     $task->log("Looking at item {$item->name} (id: {$item->id})");
                     auto_date::set_auto_date($item);
                     $completed++;
                     $items->next();
                     $task->percent_complete = $completed / $total * 100;
                     $task->set("completed", $completed);
                     $task->set("last_item_id", $item->id);
                     $task->status = t2("Examined %count items", "Examined %count items", $completed);
                     if ($completed == $total) {
                         $task->done = true;
                         $task->state = "success";
                         $task->percent_complete = 100;
                     }
                 }
         }
     } catch (Exception $e) {
         Kohana_Log::add("error", (string) $e);
         $task->done = true;
         $task->state = "error";
         $task->status = $e->getMessage();
         $errors[] = (string) $e;
     }
     if ($errors) {
         $task->log($errors);
     }
 }
Пример #22
0
 /**
  * Show a list of all available, running and finished tasks.
  */
 public function index()
 {
     $query = db::build()->update("tasks")->set("state", "stalled")->where("done", "=", 0)->where("state", "<>", "stalled")->where(db::expr("UNIX_TIMESTAMP(NOW()) - `updated` > 15"))->execute();
     $stalled_count = $query->count();
     if ($stalled_count) {
         log::warning("tasks", t2("One task is stalled", "%count tasks are stalled", $stalled_count), t('<a href="%url">view</a>', array("url" => html::mark_clean(url::site("admin/maintenance")))));
     }
     $view = new Admin_View("admin.html");
     $view->page_title = t("Maintenance tasks");
     $view->content = new View("admin_maintenance.html");
     $view->content->task_definitions = task::get_definitions();
     $view->content->running_tasks = ORM::factory("task")->where("done", "=", 0)->order_by("updated", "DESC")->find_all();
     $view->content->finished_tasks = ORM::factory("task")->where("done", "=", 1)->order_by("updated", "DESC")->find_all();
     print $view;
     // Do some maintenance while we're in here
     db::build()->delete("caches")->where("expiration", "<>", 0)->where("expiration", "<=", time())->execute();
     module::deactivate_missing_modules();
 }
Пример #23
0
 public function deleteFiles()
 {
     $fr = new FileEditResponse();
     $files = array();
     if (is_array($_POST['fID'])) {
         foreach ($_POST['fID'] as $fID) {
             $f = File::getByID($fID);
             $fp = new Permissions($f);
             if ($fp->canDeleteFile()) {
                 $files[] = $f;
                 $f->delete();
             } else {
                 throw new \Exception(t('Unable to delete one or more files.'));
             }
         }
     }
     $fr->setMessage(t2('%s file deleted successfully.', '%s files deleted successfully.', count($files)));
     $fr->outputJSON();
 }
Пример #24
0
 static function fix_mptt($task)
 {
     $start = microtime(true);
     $total = $task->get("total");
     if (empty($total)) {
         $task->set("total", $total = Database::instance()->count_records("items"));
         $task->set("stack", array(array(1, self::LEFT)));
         $task->set("ptr", 1);
         $task->set("completed", 0);
     }
     $ptr = $task->get("ptr");
     $stack = $task->get("stack");
     $completed = $task->get("completed");
     // Implement a depth-first tree walk using a stack.  Not the most efficient, but it's simple.
     while ($stack && microtime(true) - $start < 1.5) {
         list($id, $state) = array_pop($stack);
         switch ($state) {
             case self::LEFT:
                 self::set_left($id, $ptr++);
                 $item = ORM::factory("item", $id);
                 array_push($stack, array($id, self::RIGHT));
                 foreach (self::children($id) as $child) {
                     array_push($stack, array($child->id, self::LEFT));
                 }
                 break;
             case self::RIGHT:
                 self::set_right($id, $ptr++);
                 $completed++;
                 break;
         }
     }
     $task->set("stack", $stack);
     $task->set("ptr", $ptr);
     $task->set("completed", $completed);
     if ($total == $completed) {
         $task->done = true;
         $task->state = "success";
         $task->percent_complete = 100;
     } else {
         $task->percent_complete = round(100 * $completed / $total);
     }
     $task->status = t2("One row updated", "%count / %total rows updated", $completed, array("total" => $total));
 }
Пример #25
0
 static function update_gps_index($task)
 {
     $start = microtime(true);
     // Figure out the total number of photos in the database.
     // If this is the first run, also set last_id and completed to 0.
     $total = $task->get("total");
     if (empty($total)) {
         $task->set("total", $total = count(ORM::factory("item")->where("type", "=", "photo")->find_all()));
         $task->set("last_id", 0);
         $task->set("completed", 0);
     }
     $last_id = $task->get("last_id");
     $completed = $task->get("completed");
     // Generate an array of the next 100 photos to check.
     $all_photos = ORM::factory("item")->where("id", ">", $last_id)->where("type", "=", "photo")->find_all(100);
     // Check each photo in the array to see if it already has exif gps data associated with it.
     //  If it doesn't, attempt to extract gps coordinates.
     foreach (ORM::factory("item")->where("id", ">", $last_id)->where("type", "=", "photo")->find_all(100) as $item) {
         $record = ORM::factory("exif_coordinate")->where("item_id", "=", $item->id)->find();
         if (!$record->loaded()) {
             exif_gps::extract($item);
         }
         $last_id = $item->id;
         $completed++;
         if ($completed == $total || microtime(true) - $start > 1.5) {
             break;
         }
     }
     $task->set("completed", $completed);
     $task->set("last_id", $last_id);
     if ($total == $completed) {
         $task->done = true;
         $task->state = "success";
         $task->percent_complete = 100;
     } else {
         $task->percent_complete = round(100 * $completed / $total);
     }
     $task->status = t2("One photo scanned", "%count / %total photos scanned", $completed, array("total" => $total));
 }
Пример #26
0
 static function update_index($task)
 {
     $completed = $task->get("completed", 0);
     $start = microtime(true);
     foreach (ORM::factory("item")->join("search_records", "items.id", "search_records.item_id", "left")->where("search_records.item_id", null)->orwhere("search_records.dirty", 1)->find_all() as $item) {
         if (microtime(true) - $start > 1.5) {
             break;
         }
         search::update($item);
         $completed++;
     }
     list($remaining, $total, $percent) = search::stats();
     $task->set("completed", $completed);
     if ($remaining == 0 || !($remaining + $completed)) {
         $task->done = true;
         $task->state = "success";
         site_status::clear("search_index_out_of_date");
         $task->percent_complete = 100;
     } else {
         $task->percent_complete = round(100 * $completed / ($remaining + $completed));
     }
     $task->status = t2("one record updated, index is %percent% up-to-date", "%count records updated, index is %percent% up-to-date", $completed, array("percent" => $percent));
 }
 static function lowercase_passwords($task)
 {
     // Converts all passwords to lower case.
     $start = microtime(true);
     $total = $task->get("total");
     $existing_passwords = ORM::factory("items_albumpassword")->find_all();
     if (empty($total)) {
         // Set the initial values for all variables.
         $task->set("total", count($existing_passwords));
         $total = $task->get("total");
         $task->set("last_password_id", 0);
         $task->set("completed_passwords", 0);
     }
     // Retrieve the values for variables from the last time this
     //  function was run.
     $last_password_id = $task->get("last_password_id");
     $completed_passwords = $task->get("completed_passwords");
     foreach (ORM::factory("items_albumpassword")->where("id", ">", $last_password_id)->order_by("id")->find_all(100) as $one_password) {
         $one_password->password = strtolower($one_password->password);
         $one_password->save();
         $last_password_id = $one_password->id;
         $completed_passwords++;
         if ($completed_passwords == count($existing_passwords) || microtime(true) - $start > 1.5) {
             break;
         }
     }
     $task->set("last_password_id", $last_password_id);
     $task->set("completed_passwords", $completed_passwords);
     if ($completed_passwords == count($existing_passwords)) {
         $task->done = true;
         $task->state = "success";
         $task->percent_complete = 100;
     } else {
         $task->percent_complete = round(100 * $completed_passwords / count($existing_passwords));
     }
     $task->status = t2("One password fixed", "%count / %total passwords fixed", $completed_passwords, array("total" => count($existing_passwords)));
 }
Пример #28
0
 public function submit_all()
 {
     if ($this->validateAction()) {
         if ($this->permissions->canDeleteBlock() && $this->page->isMasterCollection()) {
             $name = sprintf('delete_block_%s', $this->block->getBlockID());
             $queue = \Queue::get($name);
             if ($_POST['process']) {
                 $obj = new \stdClass();
                 $messages = $queue->receive(20);
                 foreach ($messages as $key => $p) {
                     $block = unserialize($p->body);
                     $page = \Page::getByID($block['cID'], $block['cvID']);
                     $b = \Block::getByID($block['bID'], $page, $block['arHandle']);
                     if (is_object($b) && !$b->isError()) {
                         $b->deleteBlock();
                     }
                     $queue->deleteMessage($p);
                 }
                 $obj->totalItems = $queue->count();
                 if ($queue->count() == 0) {
                     $queue->deleteQueue($name);
                 }
                 $obj->bID = $this->block->getBlockID();
                 $obj->aID = $this->area->getAreaID();
                 $obj->message = t('All child blocks deleted successfully.');
                 echo json_encode($obj);
                 $this->app->shutdown();
             } else {
                 $queue = $this->block->queueForDefaultsUpdate($_POST, $queue);
             }
             $totalItems = $queue->count();
             \View::element('progress_bar', array('totalItems' => $totalItems, 'totalItemsSummary' => t2("%d block", "%d blocks", $totalItems)));
             $this->app->shutdown();
         }
     }
 }
 public function run()
 {
     $pNum = (int) Config::get('concrete.maintenance.version_job_page_num');
     $pNum = $pNum < 0 ? 1 : $pNum + 1;
     $pl = new PageList();
     $pl->ignorePermissions();
     $pl->setItemsPerPage(3);
     $pl->filter('p.cID', $pNum, '>=');
     $pl->sortByCollectionIDAscending();
     $pagination = $pl->getPagination();
     $pages = $pagination->getCurrentPageResults();
     /* probably want to keep a record of pages that have been gone through
      * so you don't start from the beginning each time..
      */
     if (!count($pages)) {
         Config::save('concrete.maintenance.version_job_page_num', 0);
         return t("All pages have been processed, starting from beginning on next run.");
     }
     $versionCount = 0;
     $pagesAffected = array();
     foreach ($pages as $page) {
         $pvl = new VersionList($page);
         $pagesAffected[] = $page->getCollectionID();
         foreach (array_slice($pvl->get(), 10) as $v) {
             if ($v instanceof Version && !$v->isApproved() && !$v->isMostRecent()) {
                 @$v->delete();
                 ++$versionCount;
             }
         }
         $pNum = $page->getCollectionID();
     }
     $pageCount = count($pagesAffected);
     Config::save('concrete.maintenance.version_job_page_num', $pNum);
     //i18n: %1$d is the number of versions deleted, %2$d is the number of affected pages, %3$d is the number of times that the Remove Old Page Versions job has been executed.
     return t2('%1$d versions deleted from %2$d page (%3$s)', '%1$d versions deleted from %2$d pages (%3$s)', $pageCount, $versionCount, $pageCount, implode(',', $pagesAffected));
 }
Пример #30
0
 /**
  * Mark thumbnails and resizes as dirty.  They will have to be rebuilt.
  */
 static function mark_dirty($thumbs, $resizes)
 {
     if ($thumbs || $resizes) {
         $db = Database::instance();
         $fields = array();
         if ($thumbs) {
             $fields["thumb_dirty"] = 1;
         }
         if ($resizes) {
             $fields["resize_dirty"] = 1;
         }
         $db->update("items", $fields, true);
     }
     $count = self::find_dirty_images_query()->count();
     if ($count) {
         site_status::warning(t2("One of your photos is out of date. <a %attrs>Click here to fix it</a>", "%count of your photos are out of date. <a %attrs>Click here to fix them</a>", $count, array("attrs" => sprintf('href="%s" class="gDialogLink"', url::site("admin/maintenance/start/gallery_task::rebuild_dirty_images?csrf=__CSRF__")))), "graphics_dirty");
     }
 }