/**
  * Helper method to write information about some redirect. Various updates
  * can be necessary if redirects are resolved as identities in SMW. The
  * title and namespace of the affected page and of its updated redirect
  * target are given. The target can be empty ('') to delete any redirect.
  * Returns the canonical ID that is now to be used for the subject.
  *
  * This method does not change the ids of the affected pages, and thus it
  * is not concerned with updates of the data that is currently stored for
  * the subject. Normally, a subject that is a redirect will not have other
  * data, but this method does not depend on this.
  *
  * @note Please make sure you fully understand this code before making any
  * changes here. Keeping the redirect structure consistent is important,
  * and errors in this code can go unnoticed for quite some time.
  *
  * @note This method merely handles the addition or deletion of a redirect
  * statement in the wiki. It does not assume that any page contents has
  * been changed (e.g. moved). See changeTitle() for additional handling in
  * this case.
  *
  * @todo Clean up this code.
  *
  * @since 1.8
  * @param string $subject_t
  * @param integer $subject_ns
  * @param string $curtarget_t
  * @param integer $curtarget_ns
  * @return integer the new canonical ID of the subject
  */
 protected function updateRedirects($subject_t, $subject_ns, $curtarget_t = '', $curtarget_ns = -1)
 {
     global $smwgQEqualitySupport, $smwgEnableUpdateJobs;
     $count = 0;
     //track count changes for redi property
     $db = $this->store->getConnection();
     // *** First get id of subject, old redirect target, and current (new) redirect target ***//
     $sid_sort = '';
     // find real id of subject, if any
     $sid = $this->store->getObjectIds()->getSMWPageIDandSort($subject_t, $subject_ns, '', '', $sid_sort, false);
     /// NOTE: $sid can be 0 here; this is useful to know since it means that fewer table updates are needed
     $new_tid = $curtarget_t ? $this->store->getObjectIds()->makeSMWPageID($curtarget_t, $curtarget_ns, '', '', false) : 0;
     // real id of new target, if given
     $old_tid = $this->store->getObjectIds()->findRedirectIdFor($subject_t, $subject_ns);
     /// NOTE: $old_tid and $new_tid both (intentionally) ignore further redirects: no redirect chains
     if ($old_tid == $new_tid) {
         // no change, all happy
         return $new_tid == 0 ? $sid : $new_tid;
     }
     // note that this means $old_tid != $new_tid in all cases below
     // *** Make relevant changes in property tables (don't write the new redirect yet) ***//
     $jobs = array();
     if ($old_tid == 0 && $sid != 0 && $smwgQEqualitySupport != SMW_EQ_NONE) {
         // new redirect
         // $smwgQEqualitySupport requires us to change all tables' page references from $sid to $new_tid.
         // Since references must not be 0, we don't have to do this is $sid == 0.
         $this->store->changeSMWPageID($sid, $new_tid, $subject_ns, $curtarget_ns, false, true);
         $jobs = $this->makeUpdateJobsForNewRedirect($subject_t, $subject_ns, $curtarget_t, $curtarget_ns);
     } elseif ($old_tid != 0) {
         // existing redirect is changed or deleted
         $this->store->getObjectIds()->deleteRedirectEntry($subject_t, $subject_ns);
         $count--;
         if ($this->store->getUpdateJobsEnabledState() && $smwgQEqualitySupport != SMW_EQ_NONE) {
             // entries that refer to old target may in fact refer to subject,
             // but we don't know which: schedule affected pages for update
             $propertyTables = $this->store->getPropertyTables();
             foreach ($propertyTables as $proptable) {
                 if ($proptable->getName() == 'smw_fpt_redi') {
                     continue;
                     // can safely be skipped
                 }
                 if ($proptable->usesIdSubject()) {
                     $from = $db->tableName($proptable->getName()) . ' INNER JOIN ' . $db->tableName(SMWSql3SmwIds::tableName) . ' ON s_id=smw_id';
                     $select = 'DISTINCT smw_title AS t,smw_namespace AS ns';
                 } else {
                     $from = $db->tableName($proptable->getName());
                     $select = 'DISTINCT s_title AS t,s_namespace AS ns';
                 }
                 if ($subject_ns === SMW_NS_PROPERTY && !$proptable->isFixedPropertyTable()) {
                     $res = $db->select($from, $select, array('p_id' => $old_tid), __METHOD__);
                     foreach ($res as $row) {
                         $title = Title::makeTitleSafe($row->ns, $row->t);
                         if (!is_null($title)) {
                             $jobs[] = new UpdateJob($title);
                         }
                     }
                     $db->freeResult($res);
                 }
                 foreach ($proptable->getFields($this->store) as $fieldname => $type) {
                     if ($type == 'p') {
                         $res = $db->select($from, $select, array($fieldname => $old_tid), __METHOD__);
                         foreach ($res as $row) {
                             $title = Title::makeTitleSafe($row->ns, $row->t);
                             if (!is_null($title)) {
                                 $jobs[] = new UpdateJob($title);
                             }
                         }
                         $db->freeResult($res);
                     }
                 }
             }
             /// NOTE: we do not update the concept cache here; this remains an offline task
         }
     }
     if ($this->store->getUpdateJobsEnabledState()) {
         JobBase::batchInsert($jobs);
     }
     // *** Finally, write the new redirect data ***//
     if ($new_tid != 0) {
         // record a new redirect
         // Redirecting done right:
         // (1) make a new ID with iw SMW_SQL3_SMWREDIIW or
         //     change iw field of current ID in this way,
         // (2) write smw_fpt_redi table,
         // (3) update canonical cache.
         // This order must be obeyed unless you really understand what you are doing!
         if ($old_tid == 0 && $smwgQEqualitySupport != SMW_EQ_NONE) {
             // mark subject as redirect (if it was no redirect before)
             if ($sid == 0) {
                 // every redirect page must have an ID
                 $sid = $this->store->getObjectIds()->makeSMWPageID($subject_t, $subject_ns, SMW_SQL3_SMWREDIIW, '', false);
             } else {
                 $db->update(SMWSql3SmwIds::tableName, array('smw_iw' => SMW_SQL3_SMWREDIIW), array('smw_id' => $sid), __METHOD__);
                 $this->store->getObjectIds()->setCache($subject_t, $subject_ns, '', '', 0, '');
                 $this->store->getObjectIds()->setCache($subject_t, $subject_ns, SMW_SQL3_SMWREDIIW, '', $sid, $sid_sort);
             }
         }
         $this->store->getObjectIds()->addRedirectForId($new_tid, $subject_t, $subject_ns);
         $count++;
     } else {
         // delete old redirect
         // This case implies $old_tid != 0 (or we would have new_tid == old_tid above).
         // Therefore $subject had a redirect, and it must also have an ID.
         // This shows that $sid != 0 here.
         if ($smwgQEqualitySupport != SMW_EQ_NONE) {
             // mark subject as non-redirect
             $db->update(SMWSql3SmwIds::tableName, array('smw_iw' => ''), array('smw_id' => $sid), __METHOD__);
             $this->store->getObjectIds()->setCache($subject_t, $subject_ns, SMW_SQL3_SMWREDIIW, '', 0, '');
             $this->store->getObjectIds()->setCache($subject_t, $subject_ns, '', '', $sid, $sid_sort);
         }
     }
     // *** Flush some caches to be safe, though they are not essential in runs with redirect updates ***//
     unset($this->store->m_semdata[$sid]);
     unset($this->store->m_semdata[$new_tid]);
     unset($this->store->m_semdata[$old_tid]);
     unset($this->store->m_sdstate[$sid]);
     unset($this->store->m_sdstate[$new_tid]);
     unset($this->store->m_sdstate[$old_tid]);
     // *** Update reference count for _REDI property ***//
     $statsTable = new PropertyStatisticsTable($db, SMWSQLStore3::PROPERTY_STATISTICS_TABLE);
     $statsTable->addToUsageCount($this->store->getObjectIds()->getSMWPropertyID(new SMWDIProperty('_REDI')), $count);
     return $new_tid == 0 ? $sid : $new_tid;
 }
 public function testAddToUsageCounts()
 {
     $statsTable = new PropertyStatisticsTable($this->getStore()->getConnection('mw.db'), \SMWSQLStore3::PROPERTY_STATISTICS_TABLE);
     $this->assertTrue($statsTable->deleteAll() !== false);
     $counts = array(1 => 42, 2 => 0, 9001 => 9001, 9002 => $this->isWinOS() ? pow(2, 30) : pow(2, 31), 9003 => 1);
     foreach ($counts as $propId => $count) {
         $this->assertTrue($statsTable->insertUsageCount($propId, $count) !== false);
     }
     $additions = array(2 => 42, 9001 => -9000, 9003 => 0);
     $this->assertTrue($statsTable->addToUsageCounts($additions) !== false);
     foreach ($additions as $propId => $addition) {
         $counts[$propId] += $addition;
     }
     $this->assertEquals($counts, $statsTable->getUsageCounts(array_keys($counts)));
 }
 /**
  * Find the numeric ID used for the page of the given normalized title,
  * namespace, interwiki, and subobjectName. Predefined IDs are not
  * taken into account (however, they would still be found correctly by
  * an avoidable database read if they are stored correctly in the
  * database; this should always be the case). In all other aspects, the
  * method works just like makeSMWPageID(). Especially, if no ID exists,
  * a new ID is created and returned.
  *
  * @since 1.8
  * @param string $title DB key
  * @param integer $namespace namespace
  * @param string $iw interwiki prefix
  * @param string $subobjectName name of subobject
  * @param boolean $canonical should redirects be resolved?
  * @param string $sortkey call-by-ref will be set to sortkey
  * @param boolean $fetchHashes should the property hashes be obtained and cached?
  * @return integer SMW id or 0 if there is none
  */
 protected function makeDatabaseId($title, $namespace, $iw, $subobjectName, $canonical, $sortkey, $fetchHashes)
 {
     $oldsort = '';
     $id = $this->getDatabaseIdAndSort($title, $namespace, $iw, $subobjectName, $oldsort, $canonical, $fetchHashes);
     $db = $this->store->getConnection('mw.db');
     $db->beginAtomicTransaction(__METHOD__);
     if ($id == 0) {
         $sortkey = $sortkey ? $sortkey : str_replace('_', ' ', $title);
         $sequenceValue = $db->nextSequenceValue($this->getIdTable() . '_smw_id_seq');
         // Bug 42659
         $db->insert(self::tableName, array('smw_id' => $sequenceValue, 'smw_title' => $title, 'smw_namespace' => $namespace, 'smw_iw' => $iw, 'smw_subobject' => $subobjectName, 'smw_sortkey' => $sortkey), __METHOD__);
         $id = (int) $db->insertId();
         // Properties also need to be in the property statistics table
         if ($namespace === SMW_NS_PROPERTY) {
             $statsStore = new PropertyStatisticsTable($db, SMWSQLStore3::PROPERTY_STATISTICS_TABLE);
             $statsStore->insertUsageCount($id, 0);
         }
         $this->setCache($title, $namespace, $iw, $subobjectName, $id, $sortkey);
         if ($fetchHashes) {
             $this->setPropertyTableHashesCache($id, null);
         }
     } elseif ($sortkey !== '' && $sortkey != $oldsort) {
         $db->update(self::tableName, array('smw_sortkey' => $sortkey), array('smw_id' => $id), __METHOD__);
         $this->setCache($title, $namespace, $iw, $subobjectName, $id, $sortkey);
     }
     $db->commitAtomicTransaction(__METHOD__);
     return $id;
 }