Esempio n. 1
0
 /**
  * Persist new or changed objects to the database container.
  *
  * Inserts or updates the database record representing this object and any
  * new or changed related object records.  Both aggregate and composite
  * related objects will be saved as appropriate, before or following the
  * save operation on the controlling instance.
  *
  * @param boolean|integer $cacheFlag Indicates if the saved object(s) should
  * be cached and optionally, by specifying an integer value, for how many
  * seconds before expiring.  Overrides the cacheFlag for the object(s).
  * @return boolean Returns true on success, false on failure.
  */
 public function save($cacheFlag = null)
 {
     if ($this->isLazy()) {
         $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Attempt to save lazy object: ' . print_r($this->toArray('', true), 1));
         return false;
     }
     $result = true;
     $sql = '';
     $pk = $this->getPrimaryKey();
     $pkn = $this->getPK();
     $pkGenerated = false;
     if ($this->isNew()) {
         $this->setDirty();
     }
     if ($this->getOption(xPDO::OPT_VALIDATE_ON_SAVE)) {
         if (!$this->validate()) {
             return false;
         }
     }
     if (!$this->xpdo->getConnection(array(xPDO::OPT_CONN_MUTABLE => true))) {
         $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not get connection for writing data", '', __METHOD__, __FILE__, __LINE__);
         return false;
     }
     $this->_saveRelatedObjects();
     if (!empty($this->_dirty)) {
         $cols = array();
         $bindings = array();
         $updateSql = array();
         foreach (array_keys($this->_dirty) as $_k) {
             if (!array_key_exists($_k, $this->_fieldMeta)) {
                 continue;
             }
             if (isset($this->_fieldMeta[$_k]['generated'])) {
                 if (!$this->_new || !isset($this->_fields[$_k]) || empty($this->_fields[$_k])) {
                     $pkGenerated = true;
                     continue;
                 }
             }
             if ($this->_fieldMeta[$_k]['phptype'] === 'password') {
                 $this->_fields[$_k] = $this->encode($this->_fields[$_k], 'password');
             }
             $fieldType = PDO::PARAM_STR;
             $fieldValue = $this->_fields[$_k];
             if (in_array($this->_fieldMeta[$_k]['phptype'], array('datetime', 'timestamp')) && !empty($this->_fieldMeta[$_k]['attributes']) && $this->_fieldMeta[$_k]['attributes'] == 'ON UPDATE CURRENT_TIMESTAMP') {
                 $this->_fields[$_k] = strftime('%Y-%m-%d %H:%M:%S');
                 continue;
             } elseif ($fieldValue === null || $fieldValue === 'NULL') {
                 if ($this->_new) {
                     continue;
                 }
                 $fieldType = PDO::PARAM_NULL;
                 $fieldValue = null;
             } elseif (in_array($this->_fieldMeta[$_k]['phptype'], array('timestamp', 'datetime')) && in_array($fieldValue, $this->xpdo->driver->_currentTimestamps, true)) {
                 $this->_fields[$_k] = strftime('%Y-%m-%d %H:%M:%S');
                 continue;
             } elseif (in_array($this->_fieldMeta[$_k]['phptype'], array('date')) && in_array($fieldValue, $this->xpdo->driver->_currentDates, true)) {
                 $this->_fields[$_k] = strftime('%Y-%m-%d');
                 continue;
             } elseif ($this->_fieldMeta[$_k]['phptype'] == 'timestamp' && preg_match('/int/i', $this->_fieldMeta[$_k]['dbtype'])) {
                 $fieldType = PDO::PARAM_INT;
             } elseif (!in_array($this->_fieldMeta[$_k]['phptype'], array('string', 'password', 'datetime', 'timestamp', 'date', 'time', 'array', 'json', 'float'))) {
                 $fieldType = PDO::PARAM_INT;
             }
             if ($this->_new) {
                 $cols[$_k] = $this->xpdo->escape($_k);
                 $bindings[":{$_k}"]['value'] = $fieldValue;
                 $bindings[":{$_k}"]['type'] = $fieldType;
             } else {
                 $bindings[":{$_k}"]['value'] = $fieldValue;
                 $bindings[":{$_k}"]['type'] = $fieldType;
                 $updateSql[] = $this->xpdo->escape($_k) . " = :{$_k}";
             }
         }
         if ($this->_new) {
             $sql = "INSERT INTO {$this->_table} (" . implode(', ', array_values($cols)) . ") VALUES (" . implode(', ', array_keys($bindings)) . ")";
         } else {
             if ($pk && $pkn) {
                 if (is_array($pkn)) {
                     $iteration = 0;
                     $where = '';
                     foreach ($pkn as $k => $v) {
                         $vt = PDO::PARAM_INT;
                         if (in_array($this->_fieldMeta[$k]['phptype'], array('string', 'float'))) {
                             $vt = PDO::PARAM_STR;
                         }
                         if ($iteration) {
                             $where .= " AND ";
                         }
                         $where .= $this->xpdo->escape($k) . " = :{$k}";
                         $bindings[":{$k}"]['value'] = $this->_fields[$k];
                         $bindings[":{$k}"]['type'] = $vt;
                         $iteration++;
                     }
                 } else {
                     $pkn = $this->getPK();
                     $pkt = PDO::PARAM_INT;
                     if (in_array($this->_fieldMeta[$pkn]['phptype'], array('string', 'float'))) {
                         $pkt = PDO::PARAM_STR;
                     }
                     $bindings[":{$pkn}"]['value'] = $pk;
                     $bindings[":{$pkn}"]['type'] = $pkt;
                     $where = $this->xpdo->escape($pkn) . ' = :' . $pkn;
                 }
                 if (!empty($updateSql)) {
                     $sql = "UPDATE {$this->_table} SET " . implode(',', $updateSql) . " WHERE {$where}";
                 }
             }
         }
         if (!empty($sql) && ($criteria = new xPDOCriteria($this->xpdo, $sql))) {
             if ($criteria->prepare()) {
                 if (!empty($bindings)) {
                     $criteria->bind($bindings, true, false);
                 }
                 if ($this->xpdo->getDebug() === true) {
                     $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Executing SQL:\n{$sql}\nwith bindings:\n" . print_r($bindings, true));
                 }
                 $tstart = microtime(true);
                 if (!($result = $criteria->stmt->execute())) {
                     $this->xpdo->queryTime += microtime(true) - $tstart;
                     $this->xpdo->executedQueries++;
                     $errorInfo = $criteria->stmt->errorInfo();
                     $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement:\n" . $criteria->toSQL() . "\n" . print_r($errorInfo, true));
                     if (($errorInfo[1] == '1146' || $errorInfo[1] == '1') && $this->getOption(xPDO::OPT_AUTO_CREATE_TABLES)) {
                         if ($this->xpdo->getManager() && $this->xpdo->manager->createObjectContainer($this->_class) === true) {
                             $tstart = microtime(true);
                             if (!($result = $criteria->stmt->execute())) {
                                 $this->xpdo->queryTime += microtime(true) - $tstart;
                                 $this->xpdo->executedQueries++;
                                 $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement:\n{$sql}\n");
                             } else {
                                 $this->xpdo->queryTime += microtime(true) - $tstart;
                                 $this->xpdo->executedQueries++;
                             }
                         } else {
                             $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $this->xpdo->errorCode() . " attempting to create object container for class {$this->_class}:\n" . print_r($this->xpdo->errorInfo(), true));
                         }
                     }
                 } else {
                     $this->xpdo->queryTime += microtime(true) - $tstart;
                     $this->xpdo->executedQueries++;
                 }
             } else {
                 $result = false;
             }
             if ($result) {
                 if ($pkn && !$pk) {
                     if ($pkGenerated) {
                         $this->_fields[$this->getPK()] = $this->xpdo->lastInsertId();
                     }
                     $pk = $this->getPrimaryKey();
                 }
                 if ($pk || !$this->getPK()) {
                     $this->_dirty = array();
                     $this->_validated = array();
                     $this->_new = false;
                 }
                 $callback = $this->getOption(xPDO::OPT_CALLBACK_ON_SAVE);
                 if ($callback && is_callable($callback)) {
                     call_user_func($callback, array('className' => $this->_class, 'criteria' => $criteria, 'object' => $this));
                 }
                 if ($this->xpdo->_cacheEnabled && $pk && ($cacheFlag || $cacheFlag === null && $this->_cacheFlag)) {
                     $cacheKey = $this->xpdo->newQuery($this->_class, $pk, $cacheFlag);
                     if (is_bool($cacheFlag)) {
                         $expires = 0;
                     } else {
                         $expires = intval($cacheFlag);
                     }
                     $this->xpdo->toCache($cacheKey, $this, $expires, array('modified' => true));
                 }
             }
         }
     }
     $this->_saveRelatedObjects();
     if ($result) {
         $this->_dirty = array();
         $this->_validated = array();
     }
     return $result;
 }
Esempio n. 2
0
if ($showUnused == 0) {
    $c->having(array('cnt > 0'));
}
if ($resources) {
    $c->where(array('Resources.resource:IN' => $resources));
}
if ($groups) {
    $c->where(array('Group.id:IN' => $groups, 'OR:Group.name:IN' => $groups, 'OR:Group.alias:IN' => $groups));
}
$c->select($modx->getSelectColumns('TaggerTag', 'TaggerTag'));
$c->select($modx->getSelectColumns('TaggerGroup', 'Group', 'group_'));
$c->select(array('cnt' => 'COUNT(Resources.tag)'));
$c->groupby($modx->getSelectColumns('TaggerTag', 'TaggerTag') . ',' . $modx->getSelectColumns('TaggerGroup', 'Group'));
$c->prepare();
$countQuery = new xPDOCriteria($modx, "SELECT COUNT(*) as total, MAX(cnt) as max_cnt FROM ({$c->toSQL(false)}) cq", $c->bindings, $c->cacheFlag);
$stmt = $countQuery->prepare();
if ($stmt && $stmt->execute()) {
    $fetchedData = $stmt->fetch(PDO::FETCH_ASSOC);
    $total = intval($fetchedData['total']);
    $maxCnt = intval($fetchedData['max_cnt']);
} else {
    $total = 0;
    $maxCnt = 0;
}
$modx->setPlaceholder($totalPh, $total);
foreach ($sort as $field => $dir) {
    $dir = strtolower($dir) == 'asc' ? 'asc' : 'desc';
    $c->sortby($field, $dir);
}
$c->limit($limit, $offset);
$tags = $modx->getIterator('TaggerTag', $c);
Esempio n. 3
0
 /**
  * Retrieves a count of xPDOObjects by the specified xPDOCriteria.
  *
  * @param string $className Class of xPDOObject to count instances of.
  * @param mixed $criteria Any valid xPDOCriteria object or expression.
  * @return integer The number of instances found by the criteria.
  */
 public function getCount($className, $criteria = null)
 {
     $count = 0;
     if ($query = $this->newQuery($className, $criteria)) {
         $stmt = null;
         $expr = '*';
         if ($pk = $this->getPK($className)) {
             if (!is_array($pk)) {
                 $pk = array($pk);
             }
             $expr = $this->getSelectColumns($className, $query->getAlias(), '', $pk);
         }
         if (isset($query->query['columns'])) {
             $query->query['columns'] = array();
         }
         if (!empty($query->query['groupby']) || !empty($query->query['having'])) {
             $query->select($expr);
             if ($query->prepare()) {
                 $countQuery = new xPDOCriteria($this, "SELECT COUNT(*) FROM ({$query->toSQL(false)}) cq", $query->bindings, $query->cacheFlag);
                 $stmt = $countQuery->prepare();
             }
         } else {
             $query->select(array("COUNT(DISTINCT {$expr})"));
             $stmt = $query->prepare();
         }
         if ($stmt && $stmt->execute()) {
             $count = intval($stmt->fetchColumn());
         }
     }
     return $count;
 }
Esempio n. 4
0
 protected function countTotal($className, xPDOQuery &$criteria)
 {
     $count = 0;
     $query = clone $criteria;
     $stmt = null;
     $expr = '*';
     if ($pk = $this->modx->getPK($className)) {
         if (!is_array($pk)) {
             $pk = array($pk);
         }
         $expr = $this->modx->getSelectColumns($className, $query->getAlias(), '', $pk);
     }
     if (isset($query->query['columns'])) {
         $query->query['columns'] = array();
     }
     if (!empty($query->query['groupby']) || !empty($query->query['having'])) {
         $query->select($expr);
         if ($query->prepare()) {
             $countQuery = new xPDOCriteria($this->modx, "SELECT COUNT(*) FROM ({$query->toSQL(false)}) cq", $query->bindings, $query->cacheFlag);
             $stmt = $countQuery->prepare();
         }
     } else {
         $query->select(array("COUNT(DISTINCT {$expr})"));
         $stmt = $query->prepare();
     }
     if ($stmt) {
         if ($stmt->execute()) {
             $count = intval($stmt->fetchColumn());
         } else {
             if ($stmt->errorCode() !== "00000") {
                 $this->modx->log(xPDO::LOG_LEVEL_ERROR, __CLASS__);
                 $this->modx->log(xPDO::LOG_LEVEL_ERROR, print_r($stmt->errorInfo(), true));
                 $this->modx->log(xPDO::LOG_LEVEL_ERROR, $query->toSQL());
             }
         }
     }
     return $count;
 }
Esempio n. 5
0
 /**
  * Gets META tag data associated with a document.
  *
  * @deprecated 2009-11-01 To be removed in 2.1
  * @param integer $id A document id, defaults to current document id.
  * @return array An array of META tag data for the specified document.
  */
 public function getMETATags($id = 0)
 {
     if (intval($id) == 0) {
         $id = intval($this->resource->id);
     }
     $query = new xPDOCriteria("SELECT smt.* " . "FROM " . $this->getTableName('modMetatag') . " smt " . "INNER JOIN " . $this->getTableName('modResourceMetatag') . " cmt ON cmt.metatag_id=smt.id " . "WHERE cmt.content_id = :id", array(':id' => $id));
     $metatags = array();
     if ($stmt = $query->prepare()) {
         if ($stmt->execute()) {
             while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                 $metatags[$row['name']] = array("tag" => $row['tag'], "tagvalue" => $row['tagvalue'], "http_equiv" => $row['http_equiv']);
             }
         }
     }
     return $metatags;
 }
Esempio n. 6
0
 function Search($query)
 {
     $this->get_execution_time();
     $query = $this->stripTags($query);
     $where = '';
     if (!empty($this->config['where']) && ($tmp = $this->modx->fromJSON($this->config['where']))) {
         if (is_array($tmp)) {
             $tmp2 = $this->modx->newQuery('modResource', $tmp);
             $tmp2->select('id');
             $tmp2->prepare();
             $tmp = $tmp2->toSQL();
             $where .= 'AND' . substr($tmp, strpos($tmp, 'WHERE') + 5);
         }
     }
     $context = !empty($this->config['context']) ? $this->config['context'] : $this->modx->resource->get('context_key');
     if (!empty($_REQUEST[$this->config['parentsVar']])) {
         $parents = $_REQUEST[$this->config['parentsVar']];
         $this->modx->setPlaceholder($this->config['plPrefix'] . 'parents', $parents);
     }
     $add_query = '';
     if (empty($this->config['showHidden'])) {
         $add_query .= ' AND `hidemenu` != 1';
     }
     if (empty($this->config['showUnpublished'])) {
         $add_query .= ' AND `published` != 0';
     }
     if (!empty($this->config['templates'])) {
         $add_query .= " AND `template` IN ({$this->config['templates']})";
     }
     if (!empty($this->config['resources'])) {
         $add_query .= " AND `rid` IN ({$this->config['resources']})";
     }
     if (!empty($parents)) {
         $tmp = explode(',', $parents);
         $arr = $tmp;
         foreach ($tmp as $v) {
             $arr = array_merge($arr, $this->modx->getChildIds($v, 10, array('context' => $context)));
         }
         $ids = implode(',', $arr);
         $add_query .= " AND `rid` IN ({$ids})";
     }
     $query_string = $this->getAllForms($query);
     $db_index = $this->modx->getTableName('ModResIndex');
     $db_res = $this->modx->getTableName('modResource');
     $sql = "SELECT COUNT(`rid`) as `id` FROM {$db_index}\n\t\t\tLEFT JOIN {$db_res} `modResource` ON {$db_index}.`rid` = `modResource`.`id`\n\t\t\tWHERE (MATCH (`resource`,`index`) AGAINST ('{$query_string}') OR `resource` LIKE '%{$query}%')\n\t\t\tAND (`modResource`.`searchable` = 1 {$add_query}) {$where}";
     $total = 0;
     $q = new xPDOCriteria($this->modx, $sql);
     if ($q->prepare() && $q->stmt->execute()) {
         if (!($total = $q->stmt->fetchColumn())) {
             return array('total' => 0, 'sql' => $sql, 'time' => $this->get_execution_time(), 'result' => '');
         }
     } else {
         $this->modx->log(modX::LOG_LEVEL_ERROR, 'Error on execution search query: ' . $sql);
     }
     $sql = "SELECT `rid`,`resource`, MATCH(`resource`,`index`) AGAINST ('>\"{$query}\" <({$query_string})' IN BOOLEAN MODE) as `rel`\n\t\t\tFROM {$db_index}\n\t\t\tLEFT JOIN {$db_res} `modResource` ON {$db_index}.`rid` = `modResource`.`id`\n\t\t\tWHERE (MATCH (`resource`,`index`) AGAINST ('>\"{$query}\" <({$query_string})' IN BOOLEAN MODE) OR `resource` LIKE '%{$query}%')\n\t\t\tAND (`modResource`.`searchable` = 1 {$add_query}) {$where}\n\t\t\tORDER BY `rel` DESC";
     if (!empty($this->config['limit'])) {
         $sql .= " LIMIT {$this->config['offset']},{$this->config['limit']}";
     }
     $q = new xPDOCriteria($this->modx, $sql);
     if ($q->prepare() && $q->stmt->execute()) {
         $result = array('total' => $total, 'sql' => $sql, 'time' => $this->get_execution_time(), 'result' => $q->stmt->fetchAll(PDO::FETCH_ASSOC));
         return $result;
     } else {
         $this->modx->log(modX::LOG_LEVEL_ERROR, 'Error on execution search query: ' . $sql);
     }
 }
 /**
  * Generates a cache entry for a MODx site Context.
  *
  * Context cache entries can override site configuration settings and are responsible for
  * loading the various lisitings and maps in the modX class, including documentListing,
  * documentMap, and eventMap.  It can also be used to setup or transform any other modX
  * properties.
  *
  * @todo Refactor the generation of documentMap, aliasMap, and
  * resourceListing so it uses less memory/file size.
  *
  * @param modContext $obj  The modContext instance to be cached.
  * @param array $options Options for system settings generation.
  * @return array An array containing all the context variable values.
  */
 public function generateContext($key, array $options = array())
 {
     $results = array();
     $obj = $this->modx->getObject('modContext', $key, true);
     if (is_object($obj) && $obj instanceof modContext && $obj->get('key')) {
         $contextConfig = $this->modx->config;
         /* generate the ContextSettings */
         $results['config'] = array();
         if ($settings = $obj->getMany('ContextSettings')) {
             foreach ($settings as $setting) {
                 $k = $setting->get('key');
                 $v = $setting->get('value');
                 $matches = array();
                 if (preg_match_all('~\\{(.*?)\\}~', $v, $matches, PREG_SET_ORDER)) {
                     $matchValue = '';
                     foreach ($matches as $match) {
                         if (isset($this->modx->config["{$match[1]}"])) {
                             $matchValue = $this->modx->config["{$match[1]}"];
                         } else {
                             $matchValue = '';
                         }
                         $v = str_replace($match[0], $matchValue, $v);
                     }
                 }
                 $results['config'][$k] = $v;
                 $contextConfig[$k] = $v;
             }
         }
         /* generate the documentMap, aliasMap, and resourceListing */
         $tblResource = $this->modx->getTableName('modResource');
         $tblContextResource = $this->modx->getTableName('modContextResource');
         $resourceFields = 'id,parent,alias,isfolder,content_type';
         if (isset($contextConfig['cache_context_resourceFields']) && $contextConfig['cache_context_resourceFields']) {
             $resourceFields = $contextConfig['cache_context_resourceFields'];
         }
         $resourceCols = $this->modx->getSelectColumns('modResource', 'r', '', explode(',', $resourceFields));
         $bindings = array(':context_key1' => array('value' => $obj->get('key'), 'type' => PDO::PARAM_STR), ':context_key2' => array('value' => $obj->get('key'), 'type' => PDO::PARAM_STR));
         $criteria = new xPDOCriteria($this->modx, "SELECT {$resourceCols} FROM {$tblResource} `r` LEFT JOIN {$tblContextResource} `cr` ON `cr`.`context_key` = :context_key1 AND `r`.`id` = `cr`.`resource` WHERE `r`.`id` != `r`.`parent` AND (`r`.`context_key` = :context_key2 OR `cr`.`context_key` IS NOT NULL) AND `r`.`deleted` = 0 GROUP BY `r`.`id` ORDER BY `r`.`parent` ASC, `r`.`menuindex` ASC", $bindings, false);
         if (!($collContentTypes = $this->modx->getCollection('modContentType'))) {
             $htmlContentType = $this->modx->newObject('modContentType');
             $htmlContentType->set('name', 'HTML');
             $htmlContentType->set('description', 'HTML content');
             $htmlContentType->set('mime_type', 'text/html');
             $htmlContentType->set('file_extensions', 'html,htm');
             $collContentTypes['1'] = $htmlContentType;
         }
         $collResources = null;
         if ($criteria->prepare() && $criteria->stmt->execute()) {
             $collResources =& $criteria->stmt;
         }
         if ($collResources) {
             $results['resourceMap'] = array();
             $results['resourceListing'] = array();
             $results['aliasMap'] = array();
             $results['documentMap'] = array();
             $containerSuffix = isset($contextConfig['container_suffix']) ? $contextConfig['container_suffix'] : '';
             while ($r = $collResources->fetch(PDO::FETCH_OBJ)) {
                 $parentId = isset($r->parent) ? strval($r->parent) : "0";
                 $results['documentMap'][] = array("{$parentId}" => (string) $r->id);
                 $results['resourceMap']["{$parentId}"][] = (string) $r->id;
                 $resourceValues = get_object_vars($r);
                 $results['resourceListing'][(string) $r->id] = $resourceValues;
                 $resAlias = '';
                 $resPath = '';
                 $contentType = isset($collContentTypes[$r->content_type]) ? $collContentTypes[$r->content_type] : $collContentTypes['1'];
                 if (isset($obj->config['friendly_urls']) && $obj->config['friendly_urls'] || $contextConfig['friendly_urls']) {
                     if (isset($obj->config['friendly_alias_urls']) && $obj->config['friendly_alias_urls'] || $contextConfig['friendly_alias_urls']) {
                         $resAlias = $r->alias;
                         if (empty($resAlias)) {
                             $resAlias = $r->id;
                         }
                         $parentResource = '';
                         if (isset($obj->config['use_alias_path']) && $obj->config['use_alias_path'] == 1 || $contextConfig['use_alias_path']) {
                             $pathParentId = $parentId;
                             $parentResources = array();
                             $currResource = $r;
                             $parentSql = "SELECT {$resourceCols} FROM {$tblResource} `r` WHERE `r`.`id` = :parent AND `r`.`id` != `r`.`parent` LIMIT 1";
                             $hasParent = (bool) $pathParentId;
                             if ($hasParent) {
                                 if ($parentStmt = $this->modx->prepare($parentSql)) {
                                     $parentStmt->bindParam(':parent', $pathParentId);
                                     if ($parentStmt->execute()) {
                                         while ($hasParent && ($currResource = $parentStmt->fetch(PDO::FETCH_OBJ))) {
                                             $parentAlias = $currResource->alias;
                                             if (empty($parentAlias)) {
                                                 $parentAlias = "{$pathParentId}";
                                             }
                                             $parentResources[] = "{$parentAlias}";
                                             $pathParentId = $currResource->parent;
                                             $hasParent = $pathParentId > 0 && $parentStmt->execute();
                                         }
                                     }
                                 }
                             }
                             $resPath = !empty($parentResources) ? implode('/', array_reverse($parentResources)) : '';
                         }
                     } else {
                         $resAlias = $r->id;
                     }
                     if (!empty($containerSuffix) && $r->isfolder) {
                         $resourceExt = $containerSuffix;
                     } else {
                         $resourceExt = $contentType->getExtension();
                     }
                     if (!empty($resourceExt)) {
                         $resAlias .= $resourceExt;
                     }
                 } else {
                     $resAlias = $r->id;
                 }
                 $results['resourceListing'][(string) $r->id]['path'] = $resPath;
                 if (!empty($resPath)) {
                     $resPath .= '/';
                 }
                 if (isset($results['aliasMap'][$resPath . $resAlias])) {
                     $this->modx->log(xPDO::LOG_LEVEL_ERROR, "Resource alias {$resPath}{$resAlias} already exists for resource id = {$results['aliasMap'][$resPath . $resAlias]}; skipping duplicate resource alias for resource id = {$r->id}");
                     continue;
                 }
                 $results['aliasMap'][$resPath . $resAlias] = $r->id;
                 $results['aliasListing']["{$resPath}{$resAlias}"] = (string) $r->id;
             }
         }
         /* generate the eventMap and pluginCache */
         $results['eventMap'] = array();
         $results['pluginCache'] = array();
         $eventMap = $this->modx->getEventMap($obj->get('key'));
         if (is_array($eventMap) && !empty($eventMap)) {
             $results['eventMap'] = $eventMap;
             $pluginIds = array();
             $this->modx->loadClass('modScript');
             foreach ($eventMap as $pluginKeys) {
                 foreach ($pluginKeys as $pluginKey) {
                     if (isset($pluginIds[$pluginKey])) {
                         continue;
                     }
                     $pluginIds[$pluginKey] = $pluginKey;
                     $plugins[$pluginKey] = $this->modx->getObject('modPlugin', intval($pluginKey), true);
                 }
             }
             if (!empty($plugins)) {
                 foreach ($plugins as $pluginId => $plugin) {
                     if (!is_object($plugin)) {
                         continue;
                     }
                     $results['pluginCache'][(string) $pluginId] = $plugin->toArray('', true);
                 }
             }
         }
         if ($this->getOption('cache_context_settings', $options, true)) {
             $options[xPDO::OPT_CACHE_KEY] = $this->getOption('cache_context_settings_key', $options, 'default');
             $options[xPDO::OPT_CACHE_HANDLER] = $this->getOption('cache_context_settings_handler', $options);
             $lifetime = intval($this->getOption(xPDO::OPT_CACHE_EXPIRES, $options, 0));
             if (!$this->set($obj->getCacheKey(), $results, $lifetime, $options)) {
                 $this->modx->log(modX::LOG_LEVEL_ERROR, 'Could not cache context settings for ' . $obj->get('key') . '.');
             }
         }
     }
     return $results;
 }
Esempio n. 8
0
 public function getEventsMeta($timestamp = '')
 {
     if ($timestamp == '') {
         $timestamp = time() - TS_ONE_DAY;
     }
     $this->setConfig('baseDate', $timestamp);
     $filter = $this->getConfig('filter');
     if (!empty($filter)) {
         if (!is_array($filter)) {
             $filter = explode(',', $filter);
         }
         $filterString = "'" . implode("','", $filter) . "'";
         $filterCondition = "AND tag.tag IN ({$filterString})";
     } else {
         $filterCondition = '';
     }
     $eventTbl = $this->xpdo->getTableName('GregorianEvent');
     $tagTbl = $this->xpdo->getTableName('GregorianTag');
     $eventTagTbl = $this->xpdo->getTableName('GregorianEventTag');
     $metaFields = array('id', 'dtstart', 'dtend', 'allday');
     $select = 'event.' . implode(', event.', $metaFields);
     $calId = $this->get('id');
     $query = new xPDOCriteria($this->xpdo, "\n            SELECT {$select} FROM {$eventTbl} as event\n            LEFT JOIN {$eventTagTbl} as eventtag ON event.id = eventtag.event\n            LEFT JOIN {$tagTbl} as tag ON eventtag.tag = tag.id\n            WHERE (`dtstart` > DATE_SUB(NOW(),INTERVAL 1 DAY)\n            OR `dtend` > DATE_SUB(NOW(),INTERVAL 1 DAY)) AND event.calendar = {$calId}\n            {$filterCondition}\n            ORDER BY dtstart ASC");
     $query->prepare();
     //$sql = $query->toSql();
     return $this->xpdo->getCollection('GregorianEvent', $query);
 }
Esempio n. 9
0
$disThread = $modx->getTableName('disThread');
$bindings = array();
$sql = "INSERT INTO {$disRead} ({$modx->getSelectColumns('disThreadRead', '', '', array('user', 'board', 'thread'))}) ";
$cSub = $modx->newQuery('disThread');
$cSub->select(array(1 => "({$userId})", $modx->getSelectColumns('disThread', 'disThread', '', array('board', 'id'))));
if (!empty($scriptProperties['lastLogin'])) {
    $cSub->where(array('post_last_on:>=' => strtotime($scriptProperties['lastLogin'])));
    if ($scriptProperties['ts'] !== false) {
        $cSub->where(array('post_last_on:<' => $scriptProperties['ts']));
    }
} else {
    if (!empty($scriptProperties['replies'])) {
        $cSub->innerJoin('disThreadParticipant', 'Participants', array("{$modx->escape('Participants')}.{$modx->escape('user')} = {$userId}", "{$modx->escape('Participants')}.{$modx->escape('thread')} = {$modx->escape('disThread')}.{$modx->escape('id')}"));
        $cSub->where(array('author_last:!=' => $userId));
    }
}
$cSub->where(array("{$modx->escape('disThread')}.{$modx->escape('id')} NOT IN ({$disReadSub->toSQL()})", 'private' => 0));
$cSub->prepare();
$sql .= $cSub->toSQL();
$criteria = new xPDOCriteria($modx, $sql);
if ($criteria->prepare()) {
    if (!empty($bindings)) {
        $criteria->bind($bindings, true, false);
    }
    if (!$criteria->stmt->execute()) {
        $errorInfo = $criteria->stmt->errorInfo();
        $modx->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement:\n" . $criteria->toSQL() . "\n" . print_r($errorInfo, true));
        return false;
    }
}
return true;