Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.20% covered (success)
90.20%
1372 / 1521
75.00% covered (warning)
75.00%
57 / 76
CRAP
0.00% covered (danger)
0.00%
0 / 1
ZObjectStore
90.20% covered (success)
90.20%
1372 / 1521
75.00% covered (warning)
75.00%
57 / 76
335.52
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getNextAvailableZid
97.50% covered (success)
97.50%
39 / 40
0.00% covered (danger)
0.00%
0 / 1
4
 getRevisionById
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 fetchZObjectByTitle
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 fetchZObject
63.16% covered (warning)
63.16%
12 / 19
0.00% covered (danger)
0.00%
0 / 1
7.80
 fetchBatchZObjects
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
3
 pushZObject
39.58% covered (danger)
39.58%
19 / 48
0.00% covered (danger)
0.00%
0 / 1
13.94
 isUndoContent
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
2.01
 preparePageUpdater
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
7.05
 createNewZObject
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 updateZObject
68.81% covered (warning)
68.81%
75 / 109
0.00% covered (danger)
0.00%
0 / 1
36.69
 isFunctionSignatureChange
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
9
 disconnectFunctionObjects
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
4.01
 updateZObjectAsSystemUser
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 deleteZObjectLabelsByZid
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 deleteZObjectLabelConflictsByZid
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 findZObjectLabelConflicts
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
4
 insertZObjectLabels
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
3.00
 insertZLanguageToLanguagesCache
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 insertZObjectLabelConflicts
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
3.00
 insertZObjectAliases
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
20
 synchroniseZObjectLabels
100.00% covered (success)
100.00%
72 / 72
100.00% covered (success)
100.00%
1 / 1
11
 synchroniseZObjectLabelConflicts
100.00% covered (success)
100.00%
54 / 54
100.00% covered (success)
100.00%
1 / 1
9
 makeLabelRowKey
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 makeConflictRowKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 fetchZidsOfType
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 getCountOfTypeInstances
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 fetchAllZids
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 fetchAllZLanguageObjects
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 fetchAllZLanguageCodes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 findCodesFromZLanguage
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 fetchAllZLanguagesWithLabels
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 fetchAllInstancedTypesWithLabels
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
3.00
 fetchAllInstancedTypes
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 getReturnTypeQuery
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
1
 getPreferredLabelsQuery
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
4
 getStringMatchCondition
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
4
 searchFunctions
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
30
 getTestStatusQuery
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
1
 getTestStatusForLatestRevisions
100.00% covered (success)
100.00%
56 / 56
100.00% covered (success)
100.00%
1 / 1
2
 findZLanguageFromCode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 findZLanguagesFromCodes
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 searchZObjectLabels
100.00% covered (success)
100.00%
56 / 56
100.00% covered (success)
100.00%
1 / 1
11
 fetchZObjectLabels
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
9
 fetchZObjectLabel
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
7
 fetchZFunctionReturnType
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 findFirstZImplementationFunction
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 findReferencedZObjectsByZFunctionIdAsList
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 findReferencedZObjectsByZFunctionId
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
2.00
 insertZFunctionReference
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 deleteZFunctionReference
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 synchroniseZFunctionReference
100.00% covered (success)
100.00%
41 / 41
100.00% covered (success)
100.00%
1 / 1
10
 findRelatedZObjectsByKeyAsList
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 findRelatedZObjectsByKey
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
2.00
 findFunctionsReferencingZObjectByKey
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 findFunctionsByRenderableIO
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 functionsByRenderableIOQuery
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
1
 getRenderableIOQuery
100.00% covered (success)
100.00%
60 / 60
100.00% covered (success)
100.00%
1 / 1
3
 findFunctionsByIOTypes
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 functionsByIOTypesQuery
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
4
 newIOTypeQuery
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
2
 insertRelatedZObjects
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 deleteRelatedZObjects
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
6.01
 synchroniseRelatedZObjects
100.00% covered (success)
100.00%
63 / 63
100.00% covered (success)
100.00%
1 / 1
10
 makeRelatedRowKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 findZTesterResult
91.67% covered (success)
91.67%
55 / 60
0.00% covered (danger)
0.00%
0 / 1
11.07
 insertZTesterResult
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
3
 isLatestRevisionTuple
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 isLatestRevision
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 deleteZFunctionFromZTesterResultsCache
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 deleteZImplementationFromZTesterResultsCache
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 deleteZTesterFromZTesterResultsCache
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 deleteZLanguageFromLanguagesCache
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 synchroniseZLanguageCodes
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
8
 removeFunctionReferenceIfImplementationOrTester
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 removeReferenceFromFunction
88.89% covered (warning)
88.89%
40 / 45
0.00% covered (danger)
0.00%
0 / 1
6.05
1<?php
2/**
3 * WikiLambda Data Access Object service
4 *
5 * @file
6 * @ingroup Extensions
7 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
8 * @license MIT
9 */
10
11namespace MediaWiki\Extension\WikiLambda;
12
13use Exception;
14use MediaWiki\CommentStore\CommentStoreComment;
15use MediaWiki\Content\ContentSerializationException;
16use MediaWiki\Content\IContentHandlerFactory;
17use MediaWiki\Context\RequestContext;
18use MediaWiki\Extension\WikiLambda\Cache\MemcachedWrapper;
19use MediaWiki\Extension\WikiLambda\Registry\ZErrorTypeRegistry;
20use MediaWiki\Extension\WikiLambda\Registry\ZLangRegistry;
21use MediaWiki\Extension\WikiLambda\Registry\ZTypeRegistry;
22use MediaWiki\Extension\WikiLambda\ZObjectContent\ZObjectContent;
23use MediaWiki\Extension\WikiLambda\ZObjectContent\ZObjectContentHandler;
24use MediaWiki\Extension\WikiLambda\ZObjectContent\ZObjectPage;
25use MediaWiki\Extension\WikiLambda\ZObjects\ZPersistentObject;
26use MediaWiki\Extension\WikiLambda\ZObjects\ZReference;
27use MediaWiki\Extension\WikiLambda\ZObjects\ZResponseEnvelope;
28use MediaWiki\Extension\WikiLambda\ZObjects\ZTypedList;
29use MediaWiki\Json\FormatJson;
30use MediaWiki\Language\MessageLocalizer;
31use MediaWiki\MainConfigNames;
32use MediaWiki\MediaWikiServices;
33use MediaWiki\Page\WikiPage;
34use MediaWiki\Page\WikiPageFactory;
35use MediaWiki\Permissions\Authority;
36use MediaWiki\RecentChanges\RecentChange;
37use MediaWiki\Revision\RevisionRecord;
38use MediaWiki\Revision\RevisionStore;
39use MediaWiki\Revision\SlotRecord;
40use MediaWiki\Storage\EditResult;
41use MediaWiki\Storage\PageUpdater;
42use MediaWiki\Title\Title;
43use MediaWiki\Title\TitleArrayFromResult;
44use MediaWiki\Title\TitleFactory;
45use MediaWiki\User\User;
46use MediaWiki\User\UserGroupManager;
47use Psr\Log\LoggerInterface;
48use Wikimedia\Rdbms\FakeResultWrapper;
49use Wikimedia\Rdbms\IConnectionProvider;
50use Wikimedia\Rdbms\IDBAccessObject;
51use Wikimedia\Rdbms\IExpression;
52use Wikimedia\Rdbms\IReadableDatabase;
53use Wikimedia\Rdbms\IResultWrapper;
54use Wikimedia\Rdbms\LikeValue;
55use Wikimedia\Rdbms\SelectQueryBuilder;
56use Wikimedia\Rdbms\Subquery;
57
58class ZObjectStore {
59
60    private MemcachedWrapper $zObjectCache;
61
62    // NOTE: This constant hard-codes user-provided content as starting from 'Z10000'. Now that the
63    // wiki has launched, change it will have unpredicatable effects.
64    private const PREDEFINED_TOP_LIMIT = 'Z9999';
65
66    public const ZOBJECT_CACHE_KEY_PREFIX = 'WikiLambdaObjectStorage';
67    public const TESTER_RESULT_CACHE_WRITE_INSERTED = 'inserted';
68    public const TESTER_RESULT_CACHE_WRITE_STALE = 'stale';
69    public const TESTER_RESULT_CACHE_WRITE_FAILED = 'failed';
70
71    /**
72     * @param IConnectionProvider $dbProvider
73     * @param TitleFactory $titleFactory
74     * @param WikiPageFactory $wikiPageFactory
75     * @param RevisionStore $revisionStore
76     * @param IContentHandlerFactory $contentHandlerFactory
77     * @param UserGroupManager $userGroupManager
78     * @param LoggerInterface $logger
79     */
80    public function __construct(
81        private readonly IConnectionProvider $dbProvider,
82        private readonly TitleFactory $titleFactory,
83        private readonly WikiPageFactory $wikiPageFactory,
84        private readonly RevisionStore $revisionStore,
85        private readonly IContentHandlerFactory $contentHandlerFactory,
86        private readonly UserGroupManager $userGroupManager,
87        private readonly LoggerInterface $logger
88    ) {
89        // Non-injected items
90        $this->zObjectCache = WikiLambdaServices::getMemcachedWrapper();
91    }
92
93    /**
94     * Find next available ZID in the database to create a new ZObject
95     *
96     * @return string Next available ZID
97     */
98    public function getNextAvailableZid(): string {
99        // Intentionally use DB_PRIMARY as we need the latest data here.
100        $dbr = $this->dbProvider->getPrimaryDatabase();
101
102        $conditions = [
103            'page_namespace' => NS_MAIN,
104            'LENGTH( page_title ) > 5',
105            $dbr->expr( 'page_title', IExpression::LIKE, new LikeValue( 'Z', $dbr->anyString() ) )
106        ];
107
108        // First try, get zid of highest page_id, skipping predefined
109        $latestZid = $dbr->newSelectQueryBuilder()
110            ->select( 'page_title' )
111            ->from( 'page' )
112            ->where( $conditions )
113            ->orderBy( 'page_id', SelectQueryBuilder::SORT_DESC )
114            ->caller( __METHOD__ )
115            ->fetchField();
116
117        if ( $latestZid === false ) {
118            $latestZid = self::PREDEFINED_TOP_LIMIT;
119        }
120        $targetZid = 'Z' . ( max( intval( substr( $latestZid, 1 ) ) + 1, 10000 ) );
121
122        // Check if target zid already exists, just in case of general zid disarray
123        // where the latest non-predefined zid is not the highest one
124        $exists = $dbr->newSelectQueryBuilder()
125            ->select( 'COUNT(*)' )
126            ->from( 'page' )
127            ->where( $conditions )
128            ->andWhere( [ 'page_title' => $targetZid ] )
129            ->caller( __METHOD__ )
130            ->fetchField();
131
132        // If Zid after latest added is available, return
133        if ( !$exists ) {
134            return $targetZid;
135        }
136
137        // If Zid after latest is not available, find Zid after highest one
138        // NOTE: this operation is much more expensive, so we should only
139        // perform it in the exceptional case that latestZid fails.
140        $highestZid = $dbr->newSelectQueryBuilder()
141            ->select( 'page_title' )
142            ->from( 'page' )
143            ->where( $conditions )
144            ->orderBy( 'CAST(SUBSTR(page_title, 2) AS INTEGER)', SelectQueryBuilder::SORT_DESC )
145            ->caller( __METHOD__ )
146            ->fetchField();
147
148        if ( $highestZid === false ) {
149            $highestZid = self::PREDEFINED_TOP_LIMIT;
150        }
151
152        $this->logger->warning(
153            __METHOD__ . ' at first got "{targetZid}" — exists; slower query gets: "Z{highestZid}".',
154            [ 'targetZid' => $targetZid, 'highestZid' => $highestZid ]
155        );
156
157        $targetZid = 'Z' . ( max( intval( substr( $highestZid, 1 ) ) + 1, 10000 ) );
158
159        return $targetZid;
160    }
161
162    /**
163     * Load a page revision from a given revision ID number.
164     * Returns null if no such revision can be found.
165     *
166     * @param int $id Revision ID of this revision
167     * @return RevisionRecord|null
168     */
169    public function getRevisionById( int $id ): ?RevisionRecord {
170        $revisionRecord = $this->revisionStore->getRevisionById( $id );
171        return $revisionRecord;
172    }
173
174    /**
175     * Fetch the ZObject given its title and return it wrapped in a ZObjectContent object
176     *
177     * When a performer is supplied the content is read for that user's audience,
178     * so a RevisionDelete'd or suppressed revision they may not see yields false;
179     * internal/system callers pass no performer and read raw.
180     *
181     * TODO: Once the security fix is deployed, make the visibility audience
182     * explicit — an $audience parameter mirroring RevisionRecord::getContent(),
183     * so the ~22 internal/system callers state RAW deliberately — rather than
184     * inferring it from whether a performer is passed. Deferred to keep this
185     * patch minimal; do it under regular code review.
186     *
187     * @param Title $title The ZObject to fetch
188     * @param int|null $requestedRevision The revision ID of the page to fetch. If unset, the latest is returned.
189     * @param Authority|null $performer User to check deletion/suppression visibility for, if any
190     * @return ZObjectContent|bool Found ZObject
191     */
192    public function fetchZObjectByTitle( Title $title, ?int $requestedRevision = null, ?Authority $performer = null ) {
193        if ( $requestedRevision ) {
194            $revision = $this->revisionStore->getRevisionByTitle( $title, $requestedRevision, 0 );
195        } else {
196            $revision = $this->revisionStore->getKnownLatestRevision( $title );
197        }
198
199        if ( !$revision ) {
200            // Return false: We should not throw exceptions that trigger more fetches (ZErrorException)
201            return false;
202        }
203
204        // NOTE: Hard-coding use of MAIN slot; if we're going the MCR route, we may wish to change this (or not).
205        // Honour deletion/suppression for a specific user; null-fail if they may not see it.
206        $audience = $performer ? RevisionRecord::FOR_THIS_USER : RevisionRecord::RAW;
207        return $revision->getContent( SlotRecord::MAIN, $audience, $performer ) ?? false;
208    }
209
210    /**
211     * Get the current ZPersistentObject of a given ZID, from the cache if available
212     *
213     * @param string $zid
214     * @return ZObjectContent|bool Cached or persisted ZObject, false if not found or invalid
215     */
216    public function fetchZObject( string $zid ) {
217        $cacheKey = $this->zObjectCache->makeKey( self::ZOBJECT_CACHE_KEY_PREFIX, $zid );
218        $cachedObject = $this->zObjectCache->get( $cacheKey );
219
220        if ( $cachedObject ) {
221            $cachedContent = ZObjectContentHandler::makeContent( $cachedObject, null, CONTENT_MODEL_ZOBJECT );
222            if ( $cachedContent->isValid() ) {
223                return $cachedContent;
224            }
225            // Something went wrong;
226            // the object stored in the cache is not valid, delete from cache and go on
227            $this->zObjectCache->delete( $cacheKey );
228        }
229
230        // Cache miss somehow; let's re-fetch the object, and stash it in the cache.
231
232        $title = Title::newFromText( $zid );
233        if ( !$title ) {
234            // Return false: We should not throw exceptions that trigger more fetches (ZErrorException)
235            return false;
236        }
237
238        $zObjectContent = $this->fetchZObjectByTitle( $title );
239        if ( !$zObjectContent || !$zObjectContent->isValid() ) {
240            // Return false: We should not throw exceptions that trigger more fetches (ZErrorException)
241            return false;
242        }
243
244        $this->zObjectCache->set(
245            $cacheKey,
246            $zObjectContent->getText(),
247            $this->zObjectCache::TTL_MONTH
248        );
249
250        return $zObjectContent;
251    }
252
253    /**
254     * Returns an array of ZPersistentObjects fetched from the DB given an array of their Zids
255     *
256     * Note that this will only fetch the latest revision of a ZObject; if you want a specific
257     * revision, you need to use ZObjectStore::fetchZObjectByTitle() instead.
258     *
259     * @param string[] $zids
260     * @return ZPersistentObject[]
261     */
262    public function fetchBatchZObjects( $zids ): array {
263        $dbr = $this->dbProvider->getReplicaDatabase();
264        $query = WikiPage::getQueryInfo();
265
266        $res = $dbr->newSelectQueryBuilder()
267            ->select( $query['fields'] )
268            ->from( 'page' )
269            ->where( [
270                'page_namespace' => NS_MAIN,
271                'page_title' => $zids
272            ] )
273            ->caller( __METHOD__ )
274            ->fetchResultSet();
275
276        $titleArray = new TitleArrayFromResult( $res );
277
278        $dataArray = [];
279        foreach ( $titleArray as $title ) {
280            // TODO (T300521): Handle error from fetchZObjectByTitle
281            $content = $this->fetchZObjectByTitle( $title );
282            if ( $content->isValid() ) {
283                $dataArray[ $title->getBaseText() ] = $content->getZObject();
284            }
285        }
286        return $dataArray;
287    }
288
289    /**
290     * Push a given Object into the Database, without validation.
291     *
292     * @param string $zid
293     * @param string $data
294     * @param string $summary
295     * @return bool True if a new revision was created; false on a null edit (no change)
296     * @throws Exception
297     */
298    public function pushZObject( string $zid, string $data, string $summary ) {
299        $title = $this->titleFactory->newFromText( $zid, NS_MAIN );
300        // Error: Failed creating title due to invalid format
301        if ( !$title ) {
302            throw new ZErrorException(
303                ZErrorFactory::createZErrorInstance(
304                    ZErrorTypeRegistry::Z_ERROR_INVALID_TITLE,
305                    [ 'title' => $zid ]
306                )
307            );
308        }
309
310        $page = $this->wikiPageFactory->newFromTitle( $title );
311        $flags = $title->exists() ? EDIT_UPDATE : EDIT_NEW;
312
313        // Create system user:
314        $creatingUserName = wfMessage( 'wikilambda-systemuser' )->inLanguage( 'en' )->text();
315        $user = User::newSystemUser( $creatingUserName, [ 'steal' => true ] );
316        $this->userGroupManager->addUserToGroup( $user, 'sysop' );
317        $this->userGroupManager->addUserToGroup( $user, 'functionmaintainer' );
318        $this->userGroupManager->addUserToGroup( $user, 'functioneer' );
319        $this->userGroupManager->addUserToGroup( $user, 'wikifunctions-staff' );
320
321        try {
322            $content = ZObjectContentHandler::makeContent( $data, $title );
323        } catch ( ZErrorException $e ) {
324            // Error: Make content will only fail if JSON is invalid
325            $this->logger->warning(
326                __METHOD__ . ' triggered an error on creating content for page "{zid}"',
327                [ 'zid' => $zid, 'exception' => $e ]
328            );
329            throw $e;
330        }
331
332        $pageUpdater = $this->preparePageUpdater( $page, $user, $content, $flags );
333
334        try {
335            $pageUpdater->saveRevision(
336                CommentStoreComment::newUnsavedComment( trim( $summary ) ),
337                $flags
338            );
339        } catch ( Exception $e ) {
340            // Error: Database or MediaWiki exception
341            $this->logger->warning(
342                __METHOD__ . ' triggered an error on publish for page "{zid}"',
343                [ 'zid' => $zid, 'exception' => $e ]
344            );
345            throw $e;
346        }
347
348        $status = $pageUpdater->getStatus();
349
350        // Error: Other saveRevision related errors
351        if ( !$status->isOK() ) {
352            $statusMessage = $status->getMessage();
353            $this->logger->info(
354                __METHOD__ . ' got a non-OK Status on publish, for page "{zid}"',
355                [ 'zid' => $zid, 'responseStatus' => var_export( $statusMessage, true ) ]
356            );
357            throw new ZErrorException(
358                ZErrorFactory::createZErrorInstance(
359                    ZErrorTypeRegistry::Z_ERROR_UNKNOWN,
360                    [ 'message' => (string)$statusMessage ]
361                )
362            );
363        }
364
365        return $status->wasRevisionCreated();
366    }
367
368    /**
369     * Check if the content is the same as the undo of revisions $undo back to $undoAfter.
370     *
371     * @param Title $title
372     * @param ZObjectContent $content
373     * @param int $undo
374     * @param int $undoAfter
375     * @return bool
376     */
377    private function isUndoContent( Title $title, ZObjectContent $content, int $undo, int $undoAfter ): bool {
378        $undoStatus = UIUtils::getUndoContent(
379            $title, $undo, $undoAfter, $this->revisionStore, $this->contentHandlerFactory
380        );
381        if ( !$undoStatus->isGood() ) {
382            return false;
383        }
384        $undoContent = $undoStatus->getValue();
385        '@phan-var ZObjectContent $undoContent';
386
387        // The editor can serialise the same object differently, so compare the canonical forms.
388        return FormatJson::encode( ZObjectUtils::canonicalize( $undoContent->getObject() ) ) ===
389            FormatJson::encode( ZObjectUtils::canonicalize( $content->getObject() ) );
390    }
391
392    /**
393     * Creates and prepares a PageUpdater for saving a ZObject revision.
394     *
395     * @param WikiPage $page
396     * @param User $user
397     * @param ZObjectContent $content
398     * @param int &$flags
399     * @return PageUpdater
400     */
401    private function preparePageUpdater(
402        WikiPage $page,
403        User $user,
404        ZObjectContent $content,
405        int &$flags
406    ): PageUpdater {
407        if ( ( $flags & EDIT_MINOR ) && !$user->isAllowed( 'minoredit' ) ) {
408            $flags &= ~EDIT_MINOR;
409        }
410
411        $pageUpdater = $page->newPageUpdater( $user );
412        $pageUpdater->setContent( SlotRecord::MAIN, $content );
413
414        $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
415        $needsPatrol = $mainConfig->get( MainConfigNames::UseRCPatrol ) ||
416            ( $mainConfig->get( MainConfigNames::UseNPPatrol ) && !$page->exists() );
417        if ( $needsPatrol && $user->authorizeWrite( 'autopatrol', $page->getTitle() ) ) {
418            $pageUpdater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
419        }
420
421        return $pageUpdater;
422    }
423
424    /**
425     * Create a new ZObject, with a newly assigned ZID, and store it in the Database
426     *
427     * @param MessageLocalizer $context The context of the action operation, for localisation of messages
428     * @param string $data
429     * @param string $summary
430     * @param User $user
431     * @return ZObjectPage
432     */
433    public function createNewZObject( MessageLocalizer $context, string $data, string $summary, User $user ) {
434        // Find all placeholder ZIDs and ZKeys and replace those with the next available ZID
435        $zid = $this->getNextAvailableZid();
436        $zObjectString = ZObjectUtils::replaceNullReferencePlaceholder( $data, $zid );
437
438        return $this->updateZObject( $context, $zid, $zObjectString, $summary, $user, EDIT_NEW );
439    }
440
441    /**
442     * Create or update a ZObject it in the Database
443     *
444     * @param MessageLocalizer $context The context of the action operation, for localisation of messages
445     * @param string $zid The ZID of the page to create/update, e.g. 'Z12345'
446     * @param string $data The ZObject's JSON to store, in string form, i.e. "{ Z1K1: "Z2", Z2K1: … }"
447     * @param string $summary An edit summary to display in the page's history, Recent Changes, watchlists, etc.
448     * @param User $user The user making the edit.
449     * @param int $flags Either EDIT_UPDATE (default) if editing or EDIT_NEW if creating a page
450     * @param int|null $baseRevId The revision ID that the edit is based on. If set, and the page
451     *  has a different latest revision, the edit fails with an edit conflict error.
452     * @param int $undo The newest revision that the edit undoes, if any
453     * @param int $undoAfter The revision that the edit restores, if any. If the edit is the same as
454     *  the undo of $undo back to $undoAfter, it is marked as an undo.
455     * @return ZObjectPage
456     */
457    public function updateZObject(
458        MessageLocalizer $context, string $zid, string $data, string $summary, User $user, int $flags = EDIT_UPDATE,
459        ?int $baseRevId = null, int $undo = 0, int $undoAfter = 0
460    ) {
461        $title = $this->titleFactory->newFromText( $zid, NS_MAIN );
462
463        // ERROR: Title is empty or invalid
464        if ( !( $title instanceof Title ) ) {
465            $error = ZErrorFactory::createZErrorInstance(
466                ZErrorTypeRegistry::Z_ERROR_INVALID_TITLE,
467                [ 'title' => $zid ]
468            );
469            return ZObjectPage::newFatal( $error );
470        }
471
472        // If edit flag or title did not exist, we are creating a new object
473        $creating = ( $flags === EDIT_NEW ) || !( $title->exists() );
474
475        try {
476            $content = ZObjectContentHandler::makeContent( $data, $title );
477        } catch ( ZErrorException $e ) {
478            $this->logger->info(
479                __METHOD__ . ': makeContent threw ZErrorException for {zid}: {message}',
480                [ 'zid' => $zid, 'message' => $e->getMessage(), 'exception' => $e ]
481            );
482            return ZObjectPage::newFatal( $e->getZError() );
483        } catch ( ContentSerializationException $mwe ) {
484            $this->logger->info(
485                __METHOD__ . ': makeContent threw ContentSerializationException for {zid}: {message}',
486                [ 'zid' => $zid, 'message' => $mwe->getMessage() ]
487            );
488            return ZObjectPage::newFatal(
489                // We can't cleanly recover the inner ZErrorException (if indeed it was even thrown by us), so
490                // for now just pass this down as a Z500, perhaps with the ErrorType as the message.
491                ZErrorFactory::createZErrorInstance(
492                    ZErrorTypeRegistry::Z_ERROR_UNKNOWN,
493                    [ 'message' => $mwe->getMessage() ]
494                )
495            );
496        }
497
498        // Error: ZObject validation errors.
499        if ( !( $content->isValid() ) ) {
500            return ZObjectPage::newFatal( $content->getErrors() );
501        }
502
503        // Validate that $zid and zObject[Z2K1] are the same
504        $zObjectId = $content->getZid();
505
506        if ( $zObjectId !== $zid ) {
507            $error = ZErrorFactory::createZErrorInstance(
508                ZErrorTypeRegistry::Z_ERROR_UNMATCHING_ZID,
509                [
510                    'zid' => $zObjectId,
511                    'title' => $zid
512                ]
513            );
514            return ZObjectPage::newFatal( $error );
515        }
516
517        $ztype = $content->getZType();
518
519        // Stop from creating and editing any types form DISALLOWED_ROOT_ZOBJECT
520        if ( in_array( $ztype, ZTypeRegistry::DISALLOWED_ROOT_ZOBJECTS ) ) {
521            $error = ZErrorFactory::createZErrorInstance(
522                ZErrorTypeRegistry::Z_ERROR_DISALLOWED_ROOT_ZOBJECT,
523                [ 'data' => $content->getZType() ]
524            );
525            return ZObjectPage::newFatal( $error );
526        }
527
528        // Find the label conflicts.
529        $labels = $content->getLabels()->getValueAsList();
530        $clashes = $this->findZObjectLabelConflicts( $zid, $ztype, $labels );
531
532        if ( count( $clashes ) > 0 ) {
533            $error = ZErrorFactory::createLabelClashZErrors( $clashes );
534            return ZObjectPage::newFatal( $error );
535        }
536
537        $page = $this->wikiPageFactory->newFromTitle( $title );
538
539        // Error: The page changed after the edit's base revision (edit conflict).
540        // Read the page from the primary DB. The save below uses this same state as the
541        // parent revision, thus a concurrent edit after this check also fails.
542        if ( !$creating && $baseRevId !== null ) {
543            $page->loadPageData( IDBAccessObject::READ_LATEST );
544            if ( $page->getLatest() !== $baseRevId ) {
545                $error = ZErrorFactory::createZErrorInstance(
546                    ZErrorTypeRegistry::Z_ERROR_UNKNOWN,
547                    [ 'message' => $context->msg( 'wikilambda-edit-conflict-error-message' )->text() ]
548                );
549                return ZObjectPage::newFatal( $error );
550            }
551        }
552
553        // Use ZObjectAuthorization service to check that the user has the required permissions
554        // while creating or editing an object
555        $fromContent = null;
556        if ( !$creating ) {
557            $currentRevision = $this->revisionStore->getKnownLatestRevision( $title );
558            $fromContent = $currentRevision->getSlots()->getContent( SlotRecord::MAIN );
559            '@phan-var ZObjectContent $fromContent';
560
561            // (T341199) A change to the signature of a function makes its implementations and
562            // testers incorrect, so disconnect them. Do this before the authorization check:
563            // the user must also have the rights to disconnect them.
564            if ( $this->isFunctionSignatureChange( $fromContent, $content ) ) {
565                $content = $this->disconnectFunctionObjects( $content );
566            }
567        }
568        $authorizationService = WikiLambdaServices::getZObjectAuthorization();
569        $status = $authorizationService->authorize( $fromContent, $content, $user, $title );
570
571        // Return AuthorizationStatus->error if authorization service failed
572        if ( !$status->isValid() ) {
573            return ZObjectPage::newFatal( $status->getErrors() );
574        }
575
576        // Run ZObjectContent field validation
577        try {
578            $content->validateFields( $context );
579        } catch ( ZErrorException $e ) {
580            return ZObjectPage::newFatal( $e->getZError() );
581        }
582
583        // (T335713) Like core, mark only an unchanged undo as an undo, so that users cannot tag other edits.
584        $isUndo = $undo > 0 && $undoAfter > 0 && $this->isUndoContent( $title, $content, $undo, $undoAfter );
585
586        $pageUpdater = $this->preparePageUpdater( $page, $user, $content, $flags );
587
588        if ( $isUndo ) {
589            $pageUpdater->setCause( PageUpdater::CAUSE_UNDO );
590            $pageUpdater->markAsRevert( EditResult::REVERT_UNDO, $undo, $undoAfter );
591            $pageUpdater->setOriginalRevisionId( $undoAfter );
592        }
593
594        // We prepare the content to be saved
595        try {
596            $pageUpdater->saveRevision(
597                CommentStoreComment::newUnsavedComment( trim( $summary ) ),
598                $flags
599            );
600        } catch ( Exception $e ) {
601            // Error: Database or a deeper MediaWiki error, e.g. a general editing rate limit
602
603            $this->logger->warning(
604                __METHOD__ . ' triggered an error on publish, e.g. rate limited, for page "{zid}"',
605                [ 'zid' => $zid, 'exception' => $e ]
606            );
607
608            if ( $e instanceof ZErrorException ) {
609                // TODO (T362236): Add the rendering language as a parameter, don't default to English
610                $errorMessage = $e->getZError()->getMessage( 'en' );
611            } else {
612                $errorMessage = $e->getMessage();
613            }
614
615            $error = ZErrorFactory::createZErrorInstance(
616                ZErrorTypeRegistry::Z_ERROR_UNKNOWN,
617                [ 'message' => $errorMessage ]
618            );
619            return ZObjectPage::newFatal( $error );
620        }
621
622        $status = $pageUpdater->getStatus();
623
624        if ( !$status->isOK() ) {
625
626            // TODO (T362246): Dependency-inject
627            $statusFormatter = MediaWikiServices::getInstance()->getFormatterFactory()
628                ->getStatusFormatter( $context );
629
630            // Error: Other saveRevision related errors
631
632            $this->logger->info(
633                __METHOD__ . ' got a non-OK Status on publish, for page "{zid}"',
634                [ 'zid' => $zid, 'responseStatus' => var_export( $status, true ) ]
635            );
636
637            $error = ZErrorFactory::createZErrorInstance(
638                ZErrorTypeRegistry::Z_ERROR_UNKNOWN,
639                [ 'message' => $statusFormatter->getMessage( $status )->plain() ]
640            );
641            return ZObjectPage::newFatal( $error );
642        }
643
644        // Success: return WikiPage
645        return ZObjectPage::newSuccess( $page );
646    }
647
648    /**
649     * Returns whether an edit changes the signature of a function: the number of
650     * inputs, the key or type of an input, or the output type.
651     *
652     * @param ZObjectContent $fromContent The latest revision of the object
653     * @param ZObjectContent $toContent The edited object
654     * @return bool
655     */
656    private function isFunctionSignatureChange( ZObjectContent $fromContent, ZObjectContent $toContent ): bool {
657        if (
658            !$fromContent->isValid() ||
659            $fromContent->getZType() !== ZTypeRegistry::Z_FUNCTION ||
660            $toContent->getZType() !== ZTypeRegistry::Z_FUNCTION
661        ) {
662            return false;
663        }
664
665        $fromObject = ZObjectUtils::canonicalize( $fromContent->getObject() );
666        $toObject = ZObjectUtils::canonicalize( $toContent->getObject() );
667        '@phan-var \stdClass $fromObject';
668        '@phan-var \stdClass $toObject';
669        $fromFunction = $fromObject->{ ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE };
670        $toFunction = $toObject->{ ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE };
671
672        if ( !ZObjectUtils::isTypeEqualTo(
673            $fromFunction->{ ZTypeRegistry::Z_FUNCTION_RETURN_TYPE },
674            $toFunction->{ ZTypeRegistry::Z_FUNCTION_RETURN_TYPE }
675        ) ) {
676            return true;
677        }
678
679        // The first item of a canonical list is the type of its items
680        $fromInputs = array_slice( $fromFunction->{ ZTypeRegistry::Z_FUNCTION_ARGUMENTS }, 1 );
681        $toInputs = array_slice( $toFunction->{ ZTypeRegistry::Z_FUNCTION_ARGUMENTS }, 1 );
682        if ( count( $fromInputs ) !== count( $toInputs ) ) {
683            return true;
684        }
685        foreach ( $fromInputs as $index => $fromInput ) {
686            $toInput = $toInputs[ $index ];
687            if (
688                $fromInput->{ ZTypeRegistry::Z_ARGUMENTDECLARATION_ID } !==
689                    $toInput->{ ZTypeRegistry::Z_ARGUMENTDECLARATION_ID } ||
690                !ZObjectUtils::isTypeEqualTo(
691                    $fromInput->{ ZTypeRegistry::Z_ARGUMENTDECLARATION_TYPE },
692                    $toInput->{ ZTypeRegistry::Z_ARGUMENTDECLARATION_TYPE }
693                )
694            ) {
695                return true;
696            }
697        }
698        return false;
699    }
700
701    /**
702     * Returns the function with empty lists of testers and implementations.
703     * If the lists are already empty, returns the same content.
704     *
705     * @param ZObjectContent $content A valid function
706     * @return ZObjectContent
707     */
708    private function disconnectFunctionObjects( ZObjectContent $content ): ZObjectContent {
709        // Canonicalize makes a copy, thus this does not change $content
710        $object = ZObjectUtils::canonicalize( $content->getObject() );
711        '@phan-var \stdClass $object';
712        $function = $object->{ ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE };
713
714        $emptyLists = [
715            ZTypeRegistry::Z_FUNCTION_TESTERS => [ ZTypeRegistry::Z_TESTER ],
716            ZTypeRegistry::Z_FUNCTION_IMPLEMENTATIONS => [ ZTypeRegistry::Z_IMPLEMENTATION ],
717        ];
718        $changed = false;
719        foreach ( $emptyLists as $key => $emptyList ) {
720            if ( ( $function->$key ?? $emptyList ) !== $emptyList ) {
721                $function->$key = $emptyList;
722                $changed = true;
723            }
724        }
725
726        if ( !$changed ) {
727            return $content;
728        }
729        return new ZObjectContent( FormatJson::encode( $object, true, FormatJson::UTF8_OK ) );
730    }
731
732    /**
733     * Create or update a ZObject it in the Database as a System User
734     *
735     * @param MessageLocalizer $context The context of the action operation, for localisation of messages
736     * @param string $zid
737     * @param string $data
738     * @param string $summary
739     * @param int $flags
740     * @return ZObjectPage
741     */
742    public function updateZObjectAsSystemUser(
743        MessageLocalizer $context, string $zid, string $data, string $summary, int $flags = EDIT_UPDATE
744    ) {
745        $creatingUserName = wfMessage( 'wikilambda-systemuser' )->inLanguage( 'en' )->text();
746        // System user must belong to all privileged groups in order to
747        // perform all zobject creation and editing actions:
748        $user = User::newSystemUser( $creatingUserName, [ 'steal' => true ] );
749        $this->userGroupManager->addUserToGroup( $user, 'sysop' );
750        $this->userGroupManager->addUserToGroup( $user, 'functionmaintainer' );
751        $this->userGroupManager->addUserToGroup( $user, 'functioneer' );
752        $this->userGroupManager->addUserToGroup( $user, 'wikifunctions-staff' );
753        // Make sure the edit will be marked as a bot edit
754        $flags |= EDIT_FORCE_BOT;
755        return $this->updateZObject( $context, $zid, $data, $summary, $user, $flags );
756    }
757
758    /**
759     * Delete the labels from the wikilambda_zobject_labels database that correspond
760     * to the given ZID.
761     *
762     * @param string $zid
763     */
764    public function deleteZObjectLabelsByZid( string $zid ): void {
765        $dbw = $this->dbProvider->getPrimaryDatabase();
766
767        $dbw->newDeleteQueryBuilder()
768            ->deleteFrom( 'wikilambda_zobject_labels' )
769            ->where( [ 'wlzl_zobject_zid' => $zid ] )
770            ->caller( __METHOD__ )->execute();
771    }
772
773    /**
774     * Delete the label conflicts from the wikilambda_zobject_label_conflicts database
775     * that correspond to the given ZID.
776     *
777     * @param string $zid
778     */
779    public function deleteZObjectLabelConflictsByZid( string $zid ): void {
780        $dbw = $this->dbProvider->getPrimaryDatabase();
781
782        $dbw->newDeleteQueryBuilder()
783            ->deleteFrom( 'wikilambda_zobject_label_conflicts' )
784            ->where(
785                $dbw->expr( 'wlzlc_existing_zid', '=', $zid )
786                    ->or( 'wlzlc_conflicting_zid', '=', $zid )
787            )
788            ->caller( __METHOD__ )->execute();
789    }
790
791    /**
792     * Query the wikilambda_zobject_labels database for primary labels that have
793     * the same combination of language code and value for a different ZID
794     * than the given in the parameters. These will be considered conflicting labels.
795     *
796     * @param string $zid
797     * @param string $ztype
798     * @param array<string,string> $labels Array of labels, where the key is the language code and the value
799     * is the string representation of the label in that language
800     * @return array Conflicts found in the wikilambda_zobject_labels database
801     */
802    public function findZObjectLabelConflicts( $zid, $ztype, $labels ): array {
803        $dbr = $this->dbProvider->getReplicaDatabase();
804
805        // remove labels with an undefined value
806        $labels = array_filter(
807            $labels, static function ( $value ) {
808                return $value !== "";
809            } );
810
811        if ( $labels === [] ) {
812            return [];
813        }
814
815        $labelConflictConditions = [];
816        foreach ( $labels as $language => $value ) {
817            $labelConflictConditions[] = $dbr->andExpr( [
818                'wlzl_language' => $language,
819                'wlzl_label' => $value,
820                'wlzl_label_primary' => true
821            ] );
822        }
823
824        $res = $dbr->newSelectQueryBuilder()
825            ->select( [ 'wlzl_zobject_zid', 'wlzl_language' ] )
826            ->from( 'wikilambda_zobject_labels' )
827            ->where( [
828                $dbr->expr( 'wlzl_zobject_zid', '!=', $zid ),
829                // TODO (T357552): Check against type, once we properly implement that.
830                // 'wlzl_type' => $ztype,
831                $dbr->orExpr( $labelConflictConditions )
832            ] )
833            ->caller( __METHOD__ )
834            ->fetchResultSet();
835
836        $conflicts = [];
837        foreach ( $res as $row ) {
838            // TODO (T362247): What if more than one conflicts with us on each language?
839            $conflicts[ $row->wlzl_language ] = $row->wlzl_zobject_zid;
840        }
841
842        return $conflicts;
843    }
844
845    /**
846     * Insert labels into the wikilambda_zobject_labels database for a given ZID and Type
847     *
848     * @param string $zid
849     * @param string $ztype
850     * @param array $labels Array of labels, where the key is the language code and the value
851     * is the string representation of the label in that language
852     * @param string|null $returnType
853     */
854    public function insertZObjectLabels( $zid, $ztype, $labels, $returnType = null ): void {
855        $dbw = $this->dbProvider->getPrimaryDatabase();
856
857        $updates = [];
858        foreach ( $labels as $language => $value ) {
859            $updates[] = [
860                'wlzl_zobject_zid' => $zid,
861                'wlzl_language' => $language,
862                'wlzl_type' => $ztype,
863                'wlzl_label' => $value,
864                'wlzl_label_normalised' => ZObjectUtils::comparableString( $value ),
865                'wlzl_label_primary' => true,
866                'wlzl_return_type' => $returnType
867            ];
868        }
869
870        // Exit early if there are no updates to make.
871        if ( count( $updates ) === 0 ) {
872            return;
873        }
874
875        $dbw->newInsertQueryBuilder()
876            ->insertInto( 'wikilambda_zobject_labels' )
877            ->rows( $updates )
878            ->caller( __METHOD__ )->execute();
879    }
880
881    /**
882     * Insert language code into the wikilambda_zlanguages database for a given ZID
883     *
884     * @param string $zid
885     * @param string $languageCode
886     */
887    public function insertZLanguageToLanguagesCache( string $zid, string $languageCode ): void {
888        $dbw = $this->dbProvider->getPrimaryDatabase();
889
890        $dbw->newInsertQueryBuilder()
891            ->insertInto( 'wikilambda_zlanguages' )
892            ->row( [ 'wlzlangs_zid' => $zid, 'wlzlangs_language' => $languageCode ] )
893            ->caller( __METHOD__ )->execute();
894    }
895
896    /**
897     * Insert label conflicts into the wikilambda_zobject_label_conflicts database for a given ZID
898     *
899     * @param string $zid
900     * @param array $conflicts Array of labels, where the key is the language code and the value
901     * is the other ZID for which this label is repeated
902     */
903    public function insertZObjectLabelConflicts( $zid, $conflicts ): void {
904        $dbw = $this->dbProvider->getPrimaryDatabase();
905
906        $updates = [];
907        foreach ( $conflicts as $language => $existingZid ) {
908            $updates[] = [
909                'wlzlc_existing_zid' => $existingZid,
910                'wlzlc_conflicting_zid' => $zid,
911                'wlzlc_language' => $language,
912            ];
913        }
914
915        // Exit early if there are no updates to make.
916        if ( count( $updates ) === 0 ) {
917            return;
918        }
919
920        $dbw->newInsertQueryBuilder()
921            ->insertInto( 'wikilambda_zobject_label_conflicts' )
922            ->rows( $updates )
923            ->caller( __METHOD__ )->execute();
924    }
925
926    /**
927     * Insert alias (secondary labels) into the wikilambda_zobject_labels database for a given ZID and Type
928     *
929     * @param string $zid
930     * @param string $ztype
931     * @param array $aliases Set of labels, where the key is the language code
932     * and the value is an array of strings
933     * @param string|null $returnType
934     */
935    public function insertZObjectAliases( $zid, $ztype, $aliases, $returnType = null ): void {
936        $dbw = $this->dbProvider->getPrimaryDatabase();
937
938        $updates = [];
939        foreach ( $aliases as $language => $stringset ) {
940            foreach ( $stringset as $value ) {
941                $updates[] = [
942                    'wlzl_zobject_zid' => $zid,
943                    'wlzl_language' => $language,
944                    'wlzl_type' => $ztype,
945                    'wlzl_label' => $value,
946                    'wlzl_label_normalised' => ZObjectUtils::comparableString( $value ),
947                    'wlzl_label_primary' => false,
948                    'wlzl_return_type' => $returnType
949                ];
950            }
951        }
952
953        if ( count( $updates ) === 0 ) {
954            return;
955        }
956
957        $dbw->newInsertQueryBuilder()
958            ->insertInto( 'wikilambda_zobject_labels' )
959            ->rows( $updates )
960            ->caller( __METHOD__ )->execute();
961    }
962
963    /**
964     * Reconcile the rows in wikilambda_zobject_labels for a given ZID with the desired
965     * set of primary labels and aliases, writing only the differences.
966     *
967     * Existing rows whose content tuple matches a desired row are preserved (their
968     * wlzl_id is re-used); unmatched existing rows are deleted by id; desired rows
969     * with no match are inserted. When the desired set is identical to the existing
970     * set, no writes are issued at all. (T300522)
971     *
972     * Eventually we could replace this with a simpler upsert(), but that would need a
973     * DB schema change.
974     *
975     * @param string $zid
976     * @param string $ztype
977     * @param array<string,string> $primaryLabels Labels keyed by language code
978     * @param array<string,string[]> $aliases Aliases keyed by language code, with a list of strings each
979     * @param string|null $returnType
980     */
981    public function synchroniseZObjectLabels(
982        string $zid,
983        string $ztype,
984        array $primaryLabels,
985        array $aliases,
986        ?string $returnType = null
987    ): void {
988        $dbw = $this->dbProvider->getPrimaryDatabase();
989
990        // Build the desired row payloads from primary labels and aliases.
991        $desiredRows = [];
992        foreach ( $primaryLabels as $language => $value ) {
993            $desiredRows[] = [
994                'wlzl_zobject_zid' => $zid,
995                'wlzl_language' => $language,
996                'wlzl_type' => $ztype,
997                'wlzl_label' => $value,
998                'wlzl_label_normalised' => ZObjectUtils::comparableString( $value ),
999                'wlzl_label_primary' => true,
1000                'wlzl_return_type' => $returnType,
1001            ];
1002        }
1003        foreach ( $aliases as $language => $stringset ) {
1004            foreach ( $stringset as $value ) {
1005                $desiredRows[] = [
1006                    'wlzl_zobject_zid' => $zid,
1007                    'wlzl_language' => $language,
1008                    'wlzl_type' => $ztype,
1009                    'wlzl_label' => $value,
1010                    'wlzl_label_normalised' => ZObjectUtils::comparableString( $value ),
1011                    'wlzl_label_primary' => false,
1012                    'wlzl_return_type' => $returnType,
1013                ];
1014            }
1015        }
1016
1017        // Read existing rows from the primary DB: replica lag could otherwise
1018        // produce spurious inserts (existing row not yet visible) or deletes.
1019        $existingRows = $dbw->newSelectQueryBuilder()
1020            ->select( [
1021                'wlzl_id',
1022                'wlzl_language',
1023                'wlzl_type',
1024                'wlzl_label',
1025                'wlzl_label_primary',
1026                'wlzl_return_type',
1027            ] )
1028            ->from( 'wikilambda_zobject_labels' )
1029            ->where( [ 'wlzl_zobject_zid' => $zid ] )
1030            ->caller( __METHOD__ )
1031            ->fetchResultSet();
1032
1033        // Bucket existing rows by their content tuple so each desired row can
1034        // claim one matching existing row (preserving its wlzl_id).
1035        $existingByKey = [];
1036        foreach ( $existingRows as $row ) {
1037            $key = self::makeLabelRowKey(
1038                $row->wlzl_language,
1039                $row->wlzl_type,
1040                $row->wlzl_label,
1041                (bool)$row->wlzl_label_primary,
1042                $row->wlzl_return_type
1043            );
1044            $existingByKey[$key][] = (int)$row->wlzl_id;
1045        }
1046
1047        $toInsert = [];
1048        foreach ( $desiredRows as $row ) {
1049            $key = self::makeLabelRowKey(
1050                $row['wlzl_language'],
1051                $row['wlzl_type'],
1052                $row['wlzl_label'],
1053                $row['wlzl_label_primary'],
1054                $row['wlzl_return_type']
1055            );
1056            if ( !empty( $existingByKey[$key] ) ) {
1057                array_shift( $existingByKey[$key] );
1058            } else {
1059                $toInsert[] = $row;
1060            }
1061        }
1062
1063        $toDeleteIds = [];
1064        foreach ( $existingByKey as $ids ) {
1065            foreach ( $ids as $id ) {
1066                $toDeleteIds[] = $id;
1067            }
1068        }
1069
1070        if ( $toDeleteIds !== [] ) {
1071            $dbw->newDeleteQueryBuilder()
1072                ->deleteFrom( 'wikilambda_zobject_labels' )
1073                ->where( [ 'wlzl_id' => $toDeleteIds ] )
1074                ->caller( __METHOD__ )->execute();
1075        }
1076
1077        if ( $toInsert !== [] ) {
1078            $dbw->newInsertQueryBuilder()
1079                ->insertInto( 'wikilambda_zobject_labels' )
1080                ->rows( $toInsert )
1081                ->caller( __METHOD__ )->execute();
1082        }
1083    }
1084
1085    /**
1086     * Reconcile the rows in wikilambda_zobject_label_conflicts touching the given ZID
1087     * with the desired set of conflicts, writing only the differences. (T300522)
1088     *
1089     * The scope mirrors deleteZObjectLabelConflictsByZid: rows where the ZID appears
1090     * as either side of the conflict. Desired rows are those where this ZID is the
1091     * conflicting (incoming) side.
1092     *
1093     * @param string $zid
1094     * @param array<string,string> $conflicts Map of language code to existing ZID that owns the label
1095     */
1096    public function synchroniseZObjectLabelConflicts( string $zid, array $conflicts ): void {
1097        $dbw = $this->dbProvider->getPrimaryDatabase();
1098
1099        $desiredRows = [];
1100        foreach ( $conflicts as $language => $existingZid ) {
1101            $desiredRows[] = [
1102                'wlzlc_existing_zid' => $existingZid,
1103                'wlzlc_conflicting_zid' => $zid,
1104                'wlzlc_language' => $language,
1105            ];
1106        }
1107
1108        $existingRows = $dbw->newSelectQueryBuilder()