We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 21508
    • 46 Posts
    Web Server: PHP 5.2.14
    Database: MySQL 5.0.91
    MODx: MODx: 1.0.5

    Есть дерево
    Статьи (1)
    Общее (11)
    Вопрос(111) - [published] => 0
    Вопрос(112) - [published] => 1
    Диагностика (12)
    Вопрос(121) - [published] => 1
    Вопрос(122) - [published] => 1
    Консультация (13)
    Вопрос(131) - [published] => 1
    Вопрос(132) - [published] => 0

    Ниже приведенный код выдает ошибку если в одной папке все документы опубликованы, и работает нормально если в каждой папке хотя бы 1 документ не опубликован.
    [tt]« MODx Parse Error »
    MODx encountered the following error while attempting to parse the requested resource:
    « PHP Parse Error »

    PHP error debug
    Error: Invalid argument supplied for foreach()
    Error type/ Nr.: Warning - 2
    File: /home/www/public_html/manager/includes/document.parser.class.inc.php(814) : eval()’d code
    Line: 366

    Parser timing
    MySQL: 0,1019 s (64 Requests)
    PHP: 1,6167 s
    Total: 1,7186 s[/tt]


    если убрать строки [tt]$rs = $modx->db->select("*", $tbl, "parent =$folder AND published =0", "createdon DESC");[/tt] или [tt]$resource[]= $row;[/tt] ошибка не выскакивает но соответственно нет и документов

    $folder=1;
    $tbl = $modx->getFullTableName('site_content');
    $d = isset($depth) ? $depth : 2;
    
    foreach($modx->getChildIds($folder, $d) as $mx) {
      $docfold=$modx->getDocument($mx);
      if ($docfold['isfolder']=='1'){
        $folder=$docfold['id'];
          $rs = $modx->db->select("*", $tbl, "parent =$folder AND published =0", "createdon DESC");
    
          if (!$rs) {
            $resource = array();
          } else {
            while ($row = $modx->db->getRow($rs)) {
             $resource[]= $row;
    //print_r ($row);
           }
         }
    
      }
    }


    Помогите разобраться , заранее благодарен.
      It’s Nice to Be Important, But It’s More Important to Be Nice
      • 21508
      • 46 Posts
      что самое интересное при команде [tt]print_r($row);[/tt] выдает 2 документа которые не опубликованы. почему выдает ошибку на [tt]$resource[]= $row;[/tt] или [tt]array_push($resource, $row);[/tt]
        It’s Nice to Be Important, But It’s More Important to Be Nice
        • 21508
        • 46 Posts
        методом тыка понял что ошибка в пагинации страницы.
        вызов снипита [[NewsManager? &folder=`5` &editformid=`158` &nrposts=`1` &paginate=`1` &clearcache=`1`]]

        код снипита
        <?php
        function nm_clear_cache() {
          // empty cache
          if($clearcache==1){
            include_once $modx->config['base_path']."manager/processors/cache_sync.class.processor.php";
            $sync = new synccache();
            $sync->setCachepath("assets/cache/");
            $sync->setReport(false);
            $sync->emptyCache(); // first empty the cache
          }
        }
        
        // paginatation enabled or disabled
        $paginate = isset($paginate)? $paginate : 0;
        
        // number of posts of which to show per page
        $nrposts = isset($nrposts) ? $nrposts : 10;
        
        // get post # to start at
        $start = isset($_REQUEST['start'])? $_REQUEST['start'] : 0;
        
        // Are friendly urls enabled?
        $furls = $modx->config['friendly_urls'];
        
        // get the chunk code to be used inside the previous <a> tag.
        $prv = isset($prv)? $modx->getChunk($prv) : "< Previous";
        
        // get the chunk code to be used inside the next <a> tag.
        $nxt = isset($nxt)? $modx->getChunk($nxt) : "Next >";
        
        // determine whether or not to always show previous next links
        $alwaysshow = isset($alwaysshow)? $alwaysshow : 0;
        
        // splitter to use of always show is disabled
        $prevnextsplitter = isset($prevnextsplitter)? $prevnextsplitter : "|";
        
        // Меняем тут // Set the folder to show the news change to what you want or call by snippet
        $folder = isset($folder) ? $folder : $modx->documentIdentifier;
        
        // Меняем тут // Page used to edit an article
        $editformid = isset($editformid) ? $editformid : $modx->documentIdentifier;
        
        // Id of page to goto after user deleted or publiched an article default to this page
        $postid = isset($postid) ? $postid : $modx->documentIdentifier;
        
        // Text to be displayed when there are no results
        $emptytext = isset($emptytext)? $emptytext : '<p>Нет документов.</p>';
        
        // Get values from a post
        $deleteid      = (isset($_REQUEST['deleteid'])      ? $_REQUEST['deleteid'] : "");
        $refreshid     = (isset($_REQUEST['refreshid'])     ? $_REQUEST['refreshid'] : "");
        $hidemenuvalue = (isset($_REQUEST['hidemenuvalue']) ? $_REQUEST['hidemenuvalue'] : "");
        $hidemenuid    = (isset($_REQUEST['hidemenuid'])    ? $_REQUEST['hidemenuid'] : "");
        $publishvalue  = (isset($_REQUEST['publishvalue'])  ? $_REQUEST['publishvalue'] : "");
        $publishid     = (isset($_REQUEST['publishid'])     ? $_REQUEST['publishid'] : "");
        
        // Global placeholders
        $showplaceholder = (isset($show) ? $modx->getChunk($show) : "Просмотр");
        $editplaceholder = (isset($edit) ? $modx->getChunk($edit) : "Ответить");
        $deleteplaceholder = (isset($delete) ? $modx->getChunk($delete) : "Удалить");
        $refreshplaceholder = (isset($refresh) ? $modx->getChunk($refresh) : "Поднять на верх");
        $publishplaceholder = (isset($publish) ? $modx->getChunk($publish) : "Опубликовать");
        $unpublishplaceholder = (isset($unpublish) ? $modx->getChunk($unpublish) : "Снять публикацию");
        // Modified (13.07.07)
        $hideinmenuplaceholder = (isset($hideinmenu) ? $modx->getChunk($hideinmenu) : "Удалить с меню");
        $showinmenuplaceholder = (isset($showinmenu) ? $modx->getChunk($showinmenu) : "Показать в меню");
        // -----
        $modx->setPlaceHolder('show', $showplaceholder);
        $modx->setPlaceHolder('edit', $editplaceholder);
        $modx->setPlaceHolder('delete', $deleteplaceholder);
        $modx->setPlaceHolder('refresh', $refreshplaceholder);
        $modx->setPlaceHolder('editformid', $editformid);
        $modx->setPlaceHolder('postid', $postid);
        $modx->setPlaceHolder('docid', $modx->documentIdentifier);
        $modx->setPlaceHolder('sepchar', ($furls == 1 ? '?' : '&'));
        
        // Row template
        $rowtemplate = (isset($rowtpl) ? $modx->getChunk($rowtpl) : "");
        if ($rowtemplate == "") {
          $rowtemplate = '
        <div class="one_asking">
        <span class="date_ask">
           [+pagetitle+]
           <span class="share_ask">[[getParent? &parentid=`[+id+]` &show=`0`]]</span>
        </span>
        
        <div class="sam_vopros">[+content+]</div>
        <a class="asker_in" href="[~68~]?service=viewprofile&username=[+UserLofin+]" target="_blank">Задал вопрос: [+UserFullName+]</a><br><br>
        </div>
              <div class="nm_button">
                <!-- Edit -->
                <form name="formedit" method="post" action="[~[+editformid+]~]">
                  <input name="editid" type="hidden" value="[+id+]" />
                  <input type="submit" class="button" name="edit" value="[+edit+]" />
                </form>
              </div>
              <!-- Start next post on new row -->
              <span class="nm_eol"> </span>';
        }
        
        // select resources
        $tbl = $modx->getFullTableName('site_content');
        $d = isset($depth) ? $depth : 2;
        
        foreach($modx->getChildIds($folder, $d) as $mx) {
          $docfold=$modx->getDocument($mx);
          if ($docfold['isfolder']=='1'){
            $folder=$docfold['id'];
              $rs = $modx->db->select("*", $tbl, "parent =$folder AND published =0", "createdon ASC");
              if (!$rs) {
                $resource = array();
              } else {
                while ($row = $modx->db->getRow($rs)) {
                  $resource[]= $row;
        
               }
           }
        
          }
        }
        
        $recordcount = count($resource);
        
        $createdon = time();
        
        $rownum = 0;
        $output = "";
        
        // Total number of posts to retrieve
        $nrtotal = isset($total) ? $total : $recordcount;
        $limit = min( $recordcount, $nrtotal );
        
        if ($recordcount < $nrposts)
        {
          $stop = $recordcount;
        } else {
          $stop = $nrposts;
        }
        
        if ($nrtotal > $recordcount) {
          $nrtotal = $recordcount;
        }
        
        // Start Pagination
        if ($paginate == 1) {
          if ($furls == 0) {
            $char = "&";
          } else if($furls == 1) {
            $char = "?";
          } else {
            $char = '&';
          }
        
          $currentpageid = $modx->documentIdentifier;
          $next = $start + $nrposts;
        
          $nextlink = "<a href='[~$currentpageid~]".$char."start=$next'>".$nxt."</a>";
          $previous = $start - $nrposts;
          $previouslink = "<a href='[~$currentpageid~]".$char."start=$previous'>".$prv."</a>";
          $limten = $nrposts + $start;
          if ($alwaysshow == 1) {
            $previousplaceholder = "<span id='nl_off'>".$prv."</span>";
            $nextplaceholder = "<span id='nl_off'>".$nxt."</span>";
          } else {
            $previousplaceholder = "";
            $nextplaceholder = "";
          }
        // Modified (13.7.07)
        //  $split = "";
          $split_prev = "";
          $split_next = "";
        
          if ($previous > -1) $split_prev = $prevnextsplitter;
          if ($next < $nrtotal)	$split_next = $prevnextsplitter;
        //  if ($previous > -1 && $next < $nrtotal) $split = $prevnextsplitter;
        // -----
          if ($previous > -1) $previousplaceholder = $previouslink;
          if ($next < $nrtotal) $nextplaceholder = $nextlink;
          if ($start < $nrtotal) $stop = $limten;
          $limiter = ($limten > $nrtotal) ? $nrtotal : $limten;
        
          $totalpages = ceil($nrtotal / $nrposts);
        // Modified (13.07.07)
          if ($totalpages > 1 ){
            for ($x = 0; $x < $totalpages; $x++) {
              $inc = $x * $nrposts;
              $display = $x + 1;
              if($inc != $start) {
                $pages .= "<a id=\"nl_page\" href='[~$currentpageid~]" . $char . "start=$inc'> ".$display." </a>";
              } else {
                $modx->setPlaceholder('current', $display);
        		$pages .= "<span id=\"nl_currentpage\"> ".$display." </span>";
              }
            }
          }
        // -----
          $modx->setPlaceholder('next', $nextplaceholder);
          $modx->setPlaceholder('previous', $previousplaceholder);
        // Modified (13.07.07)
        //  $modx->setPlaceholder('prevsplitter', $split_prev);
        //  $modx->setPlaceholder('nextsplitter', $split_next);
          //$modx->setPlaceholder('prevnextsplitter', $split);
        // -----
          $modx->setPlaceholder('start', $start+1);
          $modx->setPlaceholder('stop', $limiter);
          $modx->setPlaceholder('total', $nrtotal);
          $modx->setPlaceholder('pages', $pages);
          $modx->setPlaceholder('totalpages', $totalpages);
        }
        // End Pagination
        
        if (isset($headertpl)) {
          $output .= $modx->mergePlaceholderContent($modx->mergeChunkContent($modx->getChunk($headertpl)));
        }
        
        $output .= (($recordcount < 1) ? $emptytext."\n" : '');
        
        // For all articles
        for ($x = $start; $x < $stop; $x++, $rownum++) {
          if ($resource[$x]['createdby'] < 0) {
            // get web user name
            $tbl = $modx->getFullTableName("web_users");
          }
          else {
            // get manager user name
            $tbl = $modx->getFullTableName("manager_users");
          }
          $link = '';
        
          //perform the query
          $users = $modx->db->select("username", $tbl, "id = '".$resource[$x]['createdby']."'");
          $users_count = $modx->db->getRecordCount($users);
          if ($users_count < 1) {
            $username = "anonymous";
          } else {
            $resourceuser = $modx->fetchRow($users);
            $username     = $resourceuser['username'];
          }
        
          // Check if user updated this item.
          // We do this here so we're sure that the user is enabled to perform this action,
          // otherwise one could directly call this page with &deleteid=n to cancel any page!
          $tbl= $modx->getFullTableName("site_content");
        
        // Modified (13.07.07)
          //if ($refreshid == $resource[$x]['id']) {
        if ($refreshid == $resource[$x]['id'] && $refreshid != "") {
        // -----
            $flds = array(
                      'createdon' => $createdon,
                                 );
            $modx->db->update($flds, $tbl, "id = $refreshid");
            nm_clear_cache();
            $modx->sendRedirect($modx->makeUrl($postid));
          }
        
        // Modified (13.07.07)
          //if ($deleteid == $resource[$x]['id']) {
        // -----
          if ($deleteid == $resource[$x]['id'] && $deleteid != "") {
            $modx->db->delete($tbl, "id = $deleteid");
            nm_clear_cache();
            $modx->sendRedirect($modx->makeUrl($postid));
          }
        
          if ($hidemenuid == $resource[$x]['id'] && $hidemenuvalue != "") {
            // User changed hidemenu
            //$flds = array(
            //          'hidemenu' => $hideMenuValue,
            //                     );
        // Modified (13.07.07)
            $flds = array(
                      'hidemenu' => $hidemenuvalue,
                                 );
        // -----
            $modx->db->update($flds, $tbl, "id = $hidemenuid");
            nm_clear_cache();
            $modx->sendRedirect($modx->makeUrl($postid));
          }
        
          if ($publishid == $resource[$x]['id'] && $publishvalue != "" && $_POST[$introtext]!='') {
            $flds = array(
                      'published' => $publishvalue,
                                 );
            $modx->db->update($flds, $tbl, "id = $publishid");
            $modx->sendRedirect($modx->makeUrl($postid));
          }
        
          // Add function to confirm deletion of this article.
          $output .= '
            <script type="text/javascript" >
              function doDelete'.$resource[$x]['id'].'()
              {
                if(confirm("Delete the article \''.$resource[$x]['pagetitle'].' | '.$resource[$x]['longtitle'].'\'?"))
                {
                  return true;
                  // document.getElementById("formdelete'.$resource[$x]['id'].'").submit();
                }
                return false;
              }
            </script>';
            // End $output
        
          // Alternate background colors
          if ($rownum % 2 == 0) {
            $rowclassplaceholder = "nm_row_even";
          }
          else {
            $rowclassplaceholder = "nm_row_odd";
          }
        
          if ($resource[$x]['hidemenu'] == 1){
            $hidevalueplaceholder = '0';
            $hideplaceholder = $showinmenuplaceholder;
          }
          else {
            $hidevalueplaceholder = '1';
            $hideplaceholder = $hideinmenuplaceholder;
          }
        
          if ($resource[$x]['published'] == 1){
            $publishvalueplaceholder = '0';
            $publishplaceholder = $unpublishplaceholder;
          }
          else {
            $publishvalueplaceholder = '1';
            $publishplaceholder = $publishplaceholder;
          }
        
          // Set placeholders for document object
          foreach ($resource[$x] as $docVar => $docVarValue) {
        if ($docVar=='id'){
        $docinside = $modx->getDocument($docVarValue,'*','0');
        if ($docinside['createdby']>0) { $info = $modx->getUserInfo($docinside['createdby']); }else{ $info = $modx->getWebUserInfo($docinside['createdby']*-1); }
        if ($info['fullname']<>""){$UserFullName=$info['fullname'];}else{$UserFullName=$info['username'];}
        $modx->setPlaceholder('UserLofin', $info['username']);
        $modx->setPlaceholder('UserFullName', $UserFullName);
        }
            $modx->setPlaceholder($docVar, $docVarValue);
          }
        
          // Placeholders for the row
          $modx->setPlaceHolder('rowclass', $rowclassplaceholder);
          $modx->setPlaceHolder('id', $resource[$x]['id']);
        
        // Modified (13.07.07)
          //$modx->setPlaceHolder('hidemenuvalue', $hidevalueplaceholder);
        // -----
          $modx->setPlaceHolder('hidevalue', $hidevalueplaceholder);
          $modx->setPlaceHolder('hidemenu', $hideplaceholder);
          $modx->setPlaceHolder('publishvalue', $publishvalueplaceholder);
          $modx->setPlaceHolder('publish', $publishplaceholder);
          $modx->setPlaceHolder('title', $resource[$x]['pagetitle']);
          $modx->setPlaceHolder('pagetitle', $resource[$x]['pagetitle']);
          $modx->setPlaceHolder('longtitle', $resource[$x]['longtitle']);
          $modx->setPlaceHolder('content', $resource[$x]['content']);
          $modx->setPlaceHolder('groupe', $resource[$x]['parent']);
        
          // Set tv placeholders
          preg_match_all('~\[\+tv(.*?)\+\]~', $rowtemplate, $matches);
          $cnt = count($matches[1]);
          for($i = 0; $i < $cnt; $i++) {
            $value = $modx->getTemplateVarOutput($idname = array($matches[1][$i]), $docid = $resource[$x]['id'], $published = $resource[$x]['published']);
            $v = $value[$matches[1][$i]];
            $modx->setPlaceholder("tv".$matches[1][$i], $v);
          }
        
          // Expand the chunk code, and replace Placeholders
        // Modified (13.07.07)
          if (isset($resource[$x]['id'])){
            $output .= $modx->mergePlaceholderContent($modx->mergeChunkContent($rowtemplate));
          }
        // -----
        }
        
        if (isset($footertpl)) {
          $output .= $modx->mergePlaceholderContent($modx->mergeChunkContent($modx->getChunk($footertpl)));
        }
        
        return $output;
        ?>
        


        как исправить ошибку
          It’s Nice to Be Important, But It’s More Important to Be Nice
          • 785
          • 2,113 Posts
          Тихий ужас! Такое количество лишних запросов к базе впечатляет!
          Это ответ на первое сообщение, длинную программу дальше не смотрел.
          Надо делать примерно так (не тестировал, может, потребуются какие-то исправления):

          $folder=1;
          $tbl = $modx->getFullTableName('site_content');
          
          $result=$modx->db->select("id", $tbl, "published = '1' AND deleted = '0' AND hidemenu = '0' AND parent = '".$folder."'", "menuindex ASC");
          while ($row=$modx->db->getRow($result)) {
          	$ids=$row["id"];
          }
          $result=$modx->db->select("*", $tbl, "published = '1' AND deleted = '0' AND hidemenu = '0' AND parent IN (".implode(',',$ids).")", "menuindex ASC");
          while ($row=$modx->db->getRow($result)) {
          	print_r($row);
          }
            Создание сайтов на MODx, поддержка сайтов, поисковая оптимизация, программирование, копирайтинг
            Статьи о MODx, регулярно новые публикации
            • 21508
            • 46 Posts
            Это старый забытый NewsManager 1.3.3
            по он более или менее подходит по функционалу, WEB пользователи задают вопрос (с 1 группы), другие пользователи отвечают (с 2 группы). Без в хода в админку. сложность возникла в снипете NewsManager который выводит не отвеченные вопросы.
              It’s Nice to Be Important, But It’s More Important to Be Nice