public static function uploadFile(PromoImage $promoImage, GlobalTitle $sourceTitle, $sourceWikiId)
 {
     $sourceFile = \GlobalFile::newFromText($sourceTitle->getText(), $sourceWikiId);
     if (!$sourceFile->exists()) {
         echo "sourceFile doesn't exist" . PHP_EOL;
         return false;
     }
     $sourceImageUrl = $sourceFile->getUrl();
     $user = User::newFromName('WikiaBot');
     $imageData = new stdClass();
     $imageData->name = $promoImage->getPathname();
     $imageData->description = $imageData->comment = wfMessage('wikiahome-image-auto-uploaded-comment')->plain();
     $result = ImagesService::uploadImageFromUrl($sourceImageUrl, $imageData, $user);
     if (!$result['status']) {
         var_dump($result['errors'], $sourceImageUrl);
     }
     return $result['status'];
 }
Exemple #2
0
 /**
  * main entry point, create wiki with given parameters
  *
  * @throw CreateWikiException an exception with status of operation set
  */
 public function create()
 {
     global $wgExternalSharedDB, $wgSharedDB, $wgUser;
     $then = microtime(true);
     // Set this flag to ensure that all select operations go against master
     // Slave lag can cause random errors during wiki creation process
     global $wgForceMasterDatabase;
     $wgForceMasterDatabase = true;
     wfProfileIn(__METHOD__);
     if (wfReadOnly()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('DB is read only', self::ERROR_READONLY);
     }
     // check founder
     if ($this->mFounder->isAnon()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Founder is anon', self::ERROR_USER_IN_ANON);
     }
     // check executables
     $status = $this->checkExecutables();
     if ($status != 0) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('checkExecutables() failed', $status);
     }
     // check domains
     $status = $this->checkDomain();
     if ($status != 0) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Check domain failed', $status);
     }
     // prepare all values needed for creating wiki
     $this->prepareValues();
     // prevent domain to be registered more than once
     if (!AutoCreateWiki::lockDomain($this->mDomain)) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Domain name taken', self::ERROR_DOMAIN_NAME_TAKEN);
     }
     // start counting time
     $this->mCurrTime = wfTime();
     // check and create database
     $this->mDBw = wfGetDB(DB_MASTER, array(), $wgExternalSharedDB);
     # central
     ///
     // local database handled is handler to cluster we create new wiki.
     // It doesn't have to be the same like wikifactory cluster or db cluster
     // where Special:CreateWiki exists.
     //
     // @todo do not use hardcoded name, code below is only for test
     //
     // set $activeCluster to false if you want to create wikis on first
     // cluster
     //
     $this->mClusterDB = self::ACTIVE_CLUSTER ? "wikicities_" . self::ACTIVE_CLUSTER : "wikicities";
     $this->mNewWiki->dbw = wfGetDB(DB_MASTER, array(), $this->mClusterDB);
     // database handler, old $dbwTarget
     // check if database is creatable
     // @todo move all database creation checkers to canCreateDatabase
     if (!$this->canCreateDatabase()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('DB exists - ' . $this->mNewWiki->dbname, self::ERROR_DATABASE_ALREADY_EXISTS);
     } else {
         $this->mNewWiki->dbw->query(sprintf("CREATE DATABASE `%s`", $this->mNewWiki->dbname));
         wfDebugLog("createwiki", "Database {$this->mNewWiki->dbname} created\n", true);
     }
     /**
      * create position in wiki.factory
      * (I like sprintf construction, so sue me)
      */
     if (!$this->addToCityList()) {
         wfDebugLog("createwiki", __METHOD__ . ": Cannot set data in city_list table\n", true);
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot add wiki to city_list', self::ERROR_DATABASE_WRITE_TO_CITY_LIST_BROKEN);
     }
     // set new city_id
     $this->mNewWiki->city_id = $this->mDBw->insertId();
     if (empty($this->mNewWiki->city_id)) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot set data in city_list table. city_id is empty after insert', self::ERROR_DATABASE_WIKI_FACTORY_TABLES_BROKEN);
     }
     wfDebugLog("createwiki", __METHOD__ . ": Row added added into city_list table, city_id = {$this->mNewWiki->city_id}\n", true);
     /**
      * add domain and www.domain to the city_domains table
      */
     if (!$this->addToCityDomains()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot set data in city_domains table', self::ERROR_DATABASE_WRITE_TO_CITY_DOMAINS_BROKEN);
     }
     wfDebugLog("createwiki", __METHOD__ . ": Row added into city_domains table, city_id = {$this->mNewWiki->city_id}\n", true);
     /**
      * create image folder
      */
     global $wgEnableSwiftFileBackend;
     if (empty($wgEnableSwiftFileBackend)) {
         wfMkdirParents("{$this->mNewWiki->images_dir}");
         wfDebugLog("createwiki", __METHOD__ . ": Folder {$this->mNewWiki->images_dir} created\n", true);
     }
     // Force initialize uploader user from correct shared db
     $uploader = User::newFromName('CreateWiki script');
     $uploader->getId();
     $oldUser = $wgUser;
     $wgUser = $uploader;
     /**
      * wikifactory variables
      */
     wfDebugLog("createwiki", __METHOD__ . ": Populating city_variables\n", true);
     $this->setWFVariables();
     $tmpSharedDB = $wgSharedDB;
     $wgSharedDB = $this->mNewWiki->dbname;
     $this->mDBw->commit(__METHOD__);
     // commit shared DB changes
     /**
      * we got empty database created, now we have to create tables and
      * populate it with some default values
      */
     wfDebugLog("createwiki", __METHOD__ . ": Creating tables in database\n", true);
     $this->mNewWiki->dbw = wfGetDB(DB_MASTER, array(), $this->mNewWiki->dbname);
     if (!$this->createTables()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Creating tables not finished', self::ERROR_SQL_FILE_BROKEN);
     }
     /**
      * import language starter
      */
     if (!$this->importStarter()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Starter import failed', self::ERROR_SQL_FILE_BROKEN);
     }
     /**
      * making the wiki founder a sysop/bureaucrat
      */
     wfDebugLog("createwiki", __METHOD__ . ": Create user sysop/bureaucrat for user: {$this->mNewWiki->founderId} \n", true);
     if (!$this->addUserToGroups()) {
         wfDebugLog("createwiki", __METHOD__ . ": Create user sysop/bureaucrat for user: {$this->mNewWiki->founderId} failed \n", true);
     }
     /**
      * init site_stats table (add empty row)
      */
     $this->mNewWiki->dbw->insert("site_stats", array("ss_row_id" => "1"), __METHOD__);
     /**
      * copy default logo
      */
     $res = ImagesService::uploadImageFromUrl(self::CREATEWIKI_LOGO, (object) ['name' => 'Wiki.png'], $uploader);
     if ($res['status'] === true) {
         wfDebugLog("createwiki", __METHOD__ . ": Default logo has been uploaded\n", true);
     } else {
         wfDebugLog("createwiki", __METHOD__ . ": Default logo has not been uploaded - " . print_r($res['errors'], true) . "\n", true);
     }
     /**
      * destroy connection to newly created database
      */
     $this->waitForSlaves(__METHOD__);
     $wgSharedDB = $tmpSharedDB;
     $oHub = WikiFactoryHub::getInstance();
     $oHub->setVertical($this->mNewWiki->city_id, $this->mNewWiki->vertical, "CW Setup");
     wfDebugLog("createwiki", __METHOD__ . ": Wiki added to the vertical: {$this->mNewWiki->vertical} \n", true);
     for ($i = 0; $i < count($this->mNewWiki->categories); $i++) {
         $oHub->addCategory($this->mNewWiki->city_id, $this->mNewWiki->categories[$i]);
         wfDebugLog("createwiki", __METHOD__ . ": Wiki added to the category: {$this->mNewWiki->categories[$i]} \n", true);
     }
     /**
      * define wiki type
      */
     $wiki_type = 'default';
     /**
      * modify variables
      */
     global $wgUniversalCreationVariables;
     if (!empty($wgUniversalCreationVariables) && !empty($wiki_type) && isset($wgUniversalCreationVariables[$wiki_type])) {
         $this->addCustomSettings(0, $wgUniversalCreationVariables[$wiki_type], "universal");
         wfDebugLog("createwiki", __METHOD__ . ": Custom settings added for wiki_type: {$wiki_type} \n", true);
     }
     /**
      * set variables per language
      */
     global $wgLangCreationVariables;
     $langCreationVar = isset($wgLangCreationVariables[$wiki_type]) ? $wgLangCreationVariables[$wiki_type] : $wgLangCreationVariables;
     $this->addCustomSettings($this->mNewWiki->language, $langCreationVar, "language");
     wfDebugLog("createwiki", __METHOD__ . ": Custom settings added for wiki_type: {$wiki_type} and language: {$this->mNewWiki->language} \n", true);
     /**
      * set tags per language and per hub
      * @FIXME the switch is !@#$ creazy, but I didn't find a core function
      */
     $tags = new WikiFactoryTags($this->mNewWiki->city_id);
     $langTag = $this->mNewWiki->language;
     if ($langTag !== 'en') {
         switch ($langTag) {
             case 'pt-br':
                 $langTag = 'pt';
                 break;
             case 'zh-tw':
             case 'zh-hk':
             case 'zh-clas':
             case 'zh-class':
             case 'zh-classical':
             case 'zh-cn':
             case 'zh-hans':
             case 'zh-hant':
             case 'zh-min-':
             case 'zh-min-n':
             case 'zh-mo':
             case 'zh-sg':
             case 'zh-yue':
                 $langTag = 'zh';
                 break;
         }
         $tags->addTagsByName($langTag);
     }
     /**
      * move main page -> this code exists in CreateWikiLocalJob - so it is not needed anymore
      */
     /**
      * Unset database from mNewWiki, because database objects cannot be serialized from MW1.19
      */
     unset($this->mNewWiki->dbw);
     // Restore wgUser
     $wgUser = $oldUser;
     unset($oldUser);
     /**
      * Schedule an async task
      */
     $creationTask = new \Wikia\Tasks\Tasks\CreateNewWikiTask();
     $job_params = new stdClass();
     foreach ($this->mNewWiki as $id => $value) {
         if (!is_object($value)) {
             $job_params->{$id} = $value;
         }
     }
     // BugId:15644 - I need to pass this to CreateWikiLocalJob::changeStarterContributions
     $job_params->sDbStarter = $this->sDbStarter;
     $task_id = (new \Wikia\Tasks\AsyncTaskList())->wikiId($this->mNewWiki->city_id)->prioritize()->add($creationTask->call('postCreationSetup', $job_params))->add($creationTask->call('maintenance', rtrim($this->mNewWiki->url, "/")))->queue();
     wfDebugLog("createwiki", __METHOD__ . ": Local maintenance task added as {$task_id}\n", true);
     $this->info(__METHOD__ . ': done', ['task_id' => $task_id, 'took' => microtime(true) - $then]);
     wfProfileOut(__METHOD__);
 }
Exemple #3
0
if( empty($imageUrl) ) {
	echo 'ERROR: Invalid original image url'."\n";
	exit(3);
}

if( empty($destImageName) ) {
	echo 'ERROR: Invalid destination name'."\n";
	exit(4);
}

if( $sourceWikiId <= 0 ) {
	echo 'ERROR: Invalid source wiki id'."\n";
	exit(5);
}

$imageData = new stdClass();
$imageData->name = $destImageName;
$imageData->description = $imageData->comment = wfMsg('wikiahome-image-auto-uploaded-comment');

$result = ImagesService::uploadImageFromUrl($imageUrl, $imageData, $user);

if( $result['status'] === true ) {
	echo json_encode(array('id' => $result['page_id'], 'name' => $destImageName));
	exit(0);
} else {
	echo 'ERROR: Something went wrong with uploading the image.'."\n";
	print_r($result['errors']);
	exit(7);
}
	protected function uploadImage($imageUrl, $imageName, $wikiId, $isSliderImage = false) {
		wfProfileIn(__METHOD__);

		$success = false;

		//fb#45624
		$user = F::build('User', array('WikiaBot'), 'newFromName');
		$user = ($user instanceof User) ? $user : null;
		$imageData = new stdClass();
		$imageData->name = $imageName;
		$imageData->description = $imageData->comment = wfMsg('wikiahome-image-auto-uploaded-comment');

		$result = ImagesService::uploadImageFromUrl($imageUrl, $imageData, $user);

		if( $isSliderImage ) {
			$statusArrayKey = 'slider-images';
		} else {
			$statusArrayKey = 'main-images';
		}

		if( $result['status'] === true ) {
			$this->okuploads[$statusArrayKey][] = array('city_id' => $wikiId, 'id' => $result['page_id'], 'name' => $imageName);
			echo '.';
			$success = true;
		} else {
			if (!empty($result['errors'][0]['message']) && $result['errors'][0]['message'] === 'filerenameerror') {
				$this->fileexists[$statusArrayKey][] = $imageName;
				echo '!';
			} else {
				$this->faileduploads[$statusArrayKey][] = $imageName;
				echo '.';
			}
		}

		wfProfileOut(__METHOD__);
		return $success;
	}