bash_sync_perms.php 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442
  1. <?php
  2. /**
  3. * by plabudda 2013-10-09:
  4. *
  5. * 1. install:
  6. * - create *.plist file:
  7. * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
  8. * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
  9. * - load by launchctl:
  10. * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  11. *
  12. * 2. uninstall:
  13. * - unload from launchctl:
  14. * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  15. *
  16. * 3. debug:
  17. * - debug by www:
  18. * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
  19. * - more verbose debug:
  20. * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
  21. * - task:
  22. * /SE/se-dev-pl/bash_sync_perms.php?task=task
  23. * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
  24. * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
  25. * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
  26. *
  27. *
  28. * 4. Sync users: `ADMIN_USERS`.`A_STATUS` - OFF - manual sync from users table (groups from CRM_LISTA_ZASOBOW)
  29. * 'WAITING' - Kandydaci
  30. * 'NORMAL' - Aktywni pracownicy
  31. * 'DELETED' - Wyłączone konta
  32. * 'OFF_SOFT' - ?
  33. * 'OFF_HARD' - ?
  34. *
  35. * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
  36. * robienie katalogow dla korespondencji przy migracji na nowy typ pism
  37. #read PASSWORD
  38. #for a in `echo "select concat(ID,';---;',K_OD_KOGO,K_ZAWARTOS) from IN7_DZIENNIK_KORESP" |mysql -p$PASSWORD -uroot -Damssystem -h127.0.0.1 | sed 's/[^a-zA-Z0-9;-]/_/g' |sed 's/;---;/\./g' ` ;
  39. #do
  40. #echo mkdir $a
  41. #mkdir $a
  42. #done
  43. *do wywolania w katalogach IN/OUT:
  44. # cd IN
  45. # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
  46. *
  47. *
  48. *
  49. * DONE: koresp format: PISMA/ID/...
  50. * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
  51. * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
  52. * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogów}
  53. * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
  54. * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
  55. *
  56. *
  57. * DONE: Trigger po update/insert Koresp po aktualizacji permów plików projektu
  58. *
  59. * 5. Sync custom tables
  60. * TEST 2014-10-27: # php /Users/plabudda/rsync-dev/SE/bash_sync_perms.php biuro.biall-net.pl SyncPermsCustomTables
  61. * 5.1 Table list in CRM_CONFIG(key=_SYNC_TABLE_FILE_PERMS__TablesList)
  62. * table must be defined in .cnf--folders-{domain}.ini.php as section [{tblName}_COLUMN]
  63. * table must have fields: ID, L_APPOITMENT_USER, A_ADM_COMPANY, A_CLASSIFIED @see generateTasksNewRecords
  64. */
  65. ini_set('max_execution_time', 300);
  66. ini_set('memory_limit', '512M');
  67. define('DS', DIRECTORY_SEPARATOR);
  68. define('APP_PATH_ROOT', dirname(__FILE__));
  69. define('APP_PATH_WWW', dirname(__FILE__));
  70. define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
  71. // set ini to log errors into error log file
  72. ini_set('display_startup_errors', '0');
  73. ini_set('log_errors', '1');
  74. ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
  75. date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions
  76. require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
  77. Lib::loadClass('V');
  78. Lib::loadClass('Config');
  79. Lib::loadClass('DB');
  80. Lib::loadClass('User');
  81. Lib::loadClass('FoldersConfig');
  82. Lib::loadClass('FileUploader');
  83. if (isset($_SERVER["argv"][1])) {
  84. $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
  85. }
  86. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
  87. $info = array();
  88. $info['max_execution_time'] = ini_get('max_execution_time');
  89. $info['memory_limit'] = ini_get('memory_limit');
  90. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  91. ini_set('max_execution_time', 300);
  92. ini_set('memory_limit', '512M');
  93. $info = array();
  94. $info['max_execution_time'] = ini_get('max_execution_time');
  95. $info['memory_limit'] = ini_get('memory_limit');
  96. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  97. }
  98. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
  99. SyncPerms::run(null, null, 'users', null);
  100. }
  101. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
  102. SyncPerms::run(null, null, 'usersAll', null);
  103. }
  104. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
  105. SyncPerms::run(null, null, 'nextTask', null);
  106. }
  107. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
  108. SyncPerms::run(null, null, 'newFiles', null);
  109. }
  110. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
  111. $cmd = " ls -Rlea . ";
  112. exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
  113. //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 {file_name}";
  114. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
  115. $filesWithPermsTree = array();
  116. $lastName = '';
  117. $folderParent = '';
  118. foreach ($filesWithPerms as $line) {
  119. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  120. $fileParts = array();
  121. $filePartsArr = explode(' ', $line);
  122. $lastInd = 0;
  123. foreach ($filePartsArr as $vPart) {
  124. if ($lastInd > 7) {// file name
  125. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  126. $lastInd++;
  127. }
  128. else if (!empty($vPart) || $vPart === '0') {
  129. $fileParts[] = $vPart;
  130. $lastInd++;
  131. }
  132. }
  133. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  134. $lastName = '..';
  135. continue;
  136. }
  137. $file = new stdClass();
  138. if (!isset($fileParts[8])) {
  139. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  140. //continue;
  141. } else {
  142. // fix file name from bad chars
  143. // [8] => CV_Kowalski Mariusz`.pdf
  144. // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  145. // [11-Oct-2013 21:00:28 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2013-02-26_harmonogram_EDORADCA_Aktualny/-$harmonogram 01.2013.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  146. // [11-Oct-2013 21:00:27 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2012-04-19_oferta_gpon_sprint_po_poprawkach/-$Wycena GPON 2012 Biall-Net_spr v1.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  147. // [11-Oct-2013 20:56:25 UTC] PHP Notice: Error-cmd: chmod +a "user:prejsi allow write,append,writeattr,writeextattr,writesecurity,chown,read,execute,readattr,readextattr,readsecurity" "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1695.Projekt_glowny_dzialu_rozwoju_biznesu_oraz_dystrybucji_informacji/HANDLOWY/HANDLOWY_2012/OTOMIN/-$Otomin.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1517
  148. //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
  149. //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
  150. }
  151. echo'<pre style="max-height:230px;overflow:auto;border:1px solid red;text-align:left;">line/$fileParts/$filePartsArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($line, $fileParts, $filePartsArr));echo'</pre>';
  152. $file->name = end($fileParts);
  153. $file->path = array();
  154. if ($folderParent) $file->path[] = $folderParent;
  155. $file->path[] = end($fileParts);
  156. $file->path = implode('/', $file->path);
  157. //$file->owner = $fileParts[2];
  158. //$file->group = $fileParts[3];
  159. //$file->perms = $fileParts[0];
  160. $file->isDir = (substr($line, 0, 1) == 'd');
  161. $file->permsExt = array();
  162. $filesWithPermsTree[$file->name] = $file;
  163. $lastName = $file;
  164. }
  165. else if (substr($line, 0, 1) == ' ') {// extended perm line
  166. if ($lastName == '..') {
  167. continue;
  168. }
  169. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  170. }
  171. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  172. $folderParent = substr($line, 2, -1);
  173. }
  174. else if (substr($line, 0, 5) == 'total') {
  175. continue;
  176. }
  177. else if (empty($line)) {
  178. $folderParent = '';
  179. continue;
  180. }
  181. }
  182. echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
  183. }
  184. else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
  185. SyncPerms::run(null, null);
  186. }
  187. else {
  188. die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
  189. }
  190. if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
  191. $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
  192. $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
  193. SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  194. }
  195. class SyncPerms {
  196. public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
  197. if ($arg2 == 'addToLaunchctl') self::task__addToLaunchctl($domain);
  198. else if ($arg2 == 'newFiles') self::task__newFiles();
  199. else if ($arg2 == 'nextTask') self::task__nextTask();
  200. else if ($arg2 == 'testErrorLog') self::task__testErrorLog();
  201. else if ($arg2 == 'users') self::usersAction();
  202. else if ($arg2 == 'usersAll') self::usersAllAction();
  203. else if ($arg2 == 'SyncPermsCustomTables') self::task__SyncPermsCustomTables();
  204. else if ($arg2 == 'sendNotify') self::sendNotify();
  205. else self::task__default();
  206. }
  207. public static function task__addToLaunchctl($domain) {
  208. $plistFile = "/Library/LaunchDaemons/pl.biallnet.sync_perms.{$domain}.php.plist";
  209. system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  210. <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
  211. <plist version=\"1.0\">
  212. <dict>
  213. <key>Disabled</key>
  214. <false/>
  215. <key>Label</key>
  216. <string>pl.biallnet.sync_perms.{$domain}.php</string>
  217. <key>UserName</key>
  218. <string>root</string>
  219. <key>ProgramArguments</key>
  220. <array>
  221. <string>php</string>
  222. <string>{$_SERVER["argv"][0]}</string>
  223. <string>{$_SERVER["argv"][1]}</string>
  224. </array>
  225. <key>StartInterval</key>
  226. <integer>60</integer>
  227. </dict>
  228. </plist>
  229. \" > {$plistFile}");
  230. echo "Run as root: launchctl load {$plistFile} \n";
  231. }
  232. public static function task__newFiles() {
  233. $time = new stdClass();
  234. $time->start = time();
  235. self::newFilesAction();
  236. $time->end = time();
  237. // TODO: print operation time if DBG
  238. }
  239. public static function task__nextTask() {
  240. $time = new stdClass();
  241. $time->start = time();
  242. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
  243. self::installTable();
  244. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">installTable DONE</pre>';}
  245. self::generateTasksNewRecords();
  246. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksNewRecords DONE</pre>';}
  247. self::generateTasksUpdated();
  248. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksUpdated DONE</pre>';}
  249. $limit = V::get('_limit', 1, $_GET, 'int');
  250. for ($i = 0; $i < $limit; $i++) {
  251. $time->cur = time();
  252. if ($time->cur - $time->start > 60 * 5) {
  253. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">Force-break time('.($time->cur - $time->start).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';echo'</pre>';}
  254. break;
  255. }
  256. $task = self::nextTaskAction();
  257. if (!$task) break;
  258. }
  259. }
  260. public static function task__testErrorLog() {
  261. echo "display_errors: " . ini_get("display_errors") . "\n";
  262. echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
  263. echo "log_errors: " . ini_get("log_errors") . "\n";
  264. echo "error_reporting: " . ini_get("error_reporting") . "\n";
  265. echo "error_log: " . ini_get("error_log") . "\n";
  266. trigger_error("Notice: Test Error Log", E_USER_NOTICE);
  267. }
  268. public static function task__SyncPermsCustomTables() {
  269. $DBG_TIME = true;
  270. $dbgTime = new stdClass();
  271. $dbgTime->startTime = microtime(true);
  272. $dbgTime->lastTime = $dbgTime->startTime;
  273. $customSync = new SyncPermsCustomTables();
  274. // TODO: $customSync->run();
  275. $customSync->fetchConfig();
  276. if ($DBG_TIME) {
  277. $dbgTime->curTime = microtime(true);
  278. trigger_error("DBG:time after-fetchConfig (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  279. $dbgTime->lastTime = $dbgTime->curTime;
  280. }
  281. $customSync->installTable();
  282. if ($DBG_TIME) {
  283. $dbgTime->curTime = microtime(true);
  284. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  285. $dbgTime->lastTime = $dbgTime->curTime;
  286. }
  287. $rowId = (int)$arg3;
  288. if ($rowId > 0) {
  289. $customSync->executeTask('DEALS_TABLE', $rowId);// TODO: DEALS_TABLE ?
  290. }
  291. else {
  292. $customSync->generateTasksNewRecords();
  293. if ($DBG_TIME) {
  294. $dbgTime->curTime = microtime(true);
  295. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  296. $dbgTime->lastTime = $dbgTime->curTime;
  297. }
  298. $customSync->generateTasksUpdated();
  299. if ($DBG_TIME) {
  300. $dbgTime->curTime = microtime(true);
  301. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  302. $dbgTime->lastTime = $dbgTime->curTime;
  303. }
  304. $customSync->newFilesAction();
  305. if ($DBG_TIME) {
  306. $dbgTime->curTime = microtime(true);
  307. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  308. $dbgTime->lastTime = $dbgTime->curTime;
  309. }
  310. $limit = 1000;
  311. for ($i = 0; $i < $limit; $i++) {
  312. $loopTasksFired = 0;
  313. foreach ($customSync->_tbls as $tblName => $tblConf) {
  314. $task = $customSync->nextTaskAction($tblName);
  315. if ($DBG_TIME) {
  316. $dbgTime->curTime = microtime(true);
  317. trigger_error("DBG:time after-nextTaskAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  318. $dbgTime->lastTime = $dbgTime->curTime;
  319. }
  320. if (!$task) {
  321. // TODO: rm $tblName from config to prevent searching for task in next loops
  322. unset($customSync->_tbls[$tblName]);
  323. continue;
  324. }
  325. $loopTasksFired++;
  326. }
  327. if (!$loopTasksFired) {
  328. if ($DBG_TIME) {
  329. $dbgTime->curTime = microtime(true);
  330. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  331. $dbgTime->lastTime = $dbgTime->curTime;
  332. }
  333. break;
  334. }
  335. $i += $loopTasksFired;
  336. }
  337. }
  338. $dbgTime->endTime = microtime(true);
  339. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  340. }
  341. public static function task__default() {
  342. $DBG_TIME = false;
  343. $DBG_MEMORY = false;
  344. $dbgTime = new stdClass();
  345. $dbgTime->start = time();
  346. $dbgTime->startTime = microtime(true);
  347. $dbgTime->lastTime = $dbgTime->startTime;
  348. self::installTable();
  349. if ($DBG_TIME) {
  350. $dbgTime->curTime = microtime(true);
  351. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  352. $dbgTime->lastTime = $dbgTime->curTime;
  353. }
  354. self::generateTasksNewRecords();
  355. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
  356. if ($DBG_TIME) {
  357. $dbgTime->curTime = microtime(true);
  358. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  359. $dbgTime->lastTime = $dbgTime->curTime;
  360. }
  361. self::generateTasksUpdated();
  362. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
  363. if ($DBG_TIME) {
  364. $dbgTime->curTime = microtime(true);
  365. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  366. $dbgTime->lastTime = $dbgTime->curTime;
  367. }
  368. $dbgTime->cur = time();
  369. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  370. trigger_error("Error: time end after-init " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  371. return;
  372. }
  373. self::newFilesAction();
  374. if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
  375. if ($DBG_TIME) {
  376. $dbgTime->curTime = microtime(true);
  377. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  378. $dbgTime->lastTime = $dbgTime->curTime;
  379. }
  380. $limit = 100;
  381. for ($i = 0; $i < $limit; $i++) {
  382. $dbgTime->cur = time();
  383. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  384. trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  385. return;
  386. }
  387. $task = self::nextTaskAction();
  388. if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
  389. if ($DBG_TIME) {
  390. $dbgTime->curTime = microtime(true);
  391. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  392. $dbgTime->lastTime = $dbgTime->curTime;
  393. }
  394. if (!$task) {
  395. $dbgTime->cur = time();
  396. break;
  397. }
  398. }
  399. $customSync = new SyncPermsCustomTables();
  400. $customSync->run();
  401. $dbgTime->cur = time();
  402. $dbgTime->endTime = microtime(true);
  403. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  404. if ($DBG_TIME) {
  405. $dbgTime->curTime = microtime(true);
  406. trigger_error("DBG:time sync end OK (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  407. $dbgTime->lastTime = $dbgTime->curTime;
  408. }
  409. self::sendNotify();
  410. Lib::loadClass('Router');
  411. echo "DBG: UrlAction_WmsGenerate->doGenerate() START...\n";
  412. Router::getRoute('UrlAction_WmsGenerate')->doGenerate();
  413. echo "DBG: UrlAction_WmsGenerate->doGenerate() END\n";
  414. echo "DBG: UrlAction_BiAuditGenerate->doGenerate() START...\n";
  415. //Router::getRoute('UrlAction_BiAuditGenerate')->doGenerate();
  416. echo "DBG: UrlAction_BiAuditGenerate->doGenerate() END\n";
  417. }
  418. public static function sendNotify() {
  419. Lib::loadClass('Router');
  420. $cronTaskName = 'sendNotify';
  421. $keyToken = 'bach_sync_perms';
  422. $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
  423. echo "DBG: token = '{$token}'" . "\n";
  424. $string = Router::getRoute('Cron')->executeCurlTastByToken($cronTaskName, $keyToken, $token);
  425. echo "DBG: string -----------------------\n{$string}\nEOF string---------------------------------\n";
  426. }
  427. public static function installTable() {
  428. $db = DB::getDB();
  429. if (!$db) die("DB Error: No DB! L." . __LINE__);
  430. $sql = "
  431. CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
  432. `ID` int(11) NOT NULL AUTO_INCREMENT,
  433. `ID_PROJECT` int(11) NOT NULL,
  434. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  435. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  436. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  437. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  438. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  439. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  440. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  441. PRIMARY KEY (`ID`),
  442. UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
  443. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  444. ";
  445. $db->query($sql);
  446. $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
  447. $db->query($sql);
  448. $sql = "
  449. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
  450. FOR EACH ROW BEGIN
  451. IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
  452. update `_SYNC_FILE_PERMS` as s set
  453. s.`A_SYNCHRONIZED`=0
  454. where
  455. s.`ID_PROJECT`=NEW.`ID_PROJECT`
  456. or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
  457. END IF;
  458. END
  459. ";
  460. $db->query($sql);
  461. $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
  462. $db->query($sql);
  463. $sql = "
  464. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
  465. FOR EACH ROW BEGIN
  466. IF NEW.`ID_PROJECT` > 0 THEN
  467. update `_SYNC_FILE_PERMS` as s set
  468. s.`A_SYNCHRONIZED`=0
  469. where
  470. s.`ID_PROJECT`=NEW.`ID_PROJECT`;
  471. END IF;
  472. END
  473. ";
  474. $db->query($sql);
  475. if (V::get('DBG', '', $_GET, 'int') > 0) {
  476. if ($db->has_errors()) {
  477. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB errors (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
  478. }
  479. }
  480. }
  481. public static function newFilesAction() {
  482. $task = self::getTaskNewFiles();
  483. $taskResult = self::fixLastModifiedFiles($task);
  484. self::saveTask(-1);
  485. }
  486. public static function nextTaskAction() {
  487. $task = self::getTask();
  488. if (!$task) return false;
  489. self::executeTask($task);
  490. /*
  491. if (isset($task->A_SYNC_RESULT->total)
  492. && isset($task->A_SYNC_RESULT->lastDone)
  493. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  494. ) {
  495. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  496. } else {
  497. self::saveTask($task->ID_PROJECT);
  498. }
  499. */
  500. self::saveTask($task->ID_PROJECT);
  501. return $task;
  502. }
  503. public static function generateTasksUpdated() {
  504. $db = DB::getDB();
  505. if (!$db) die("DB Error: No DB! L." . __LINE__);
  506. $sqlTest = "select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
  507. from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  508. where
  509. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  510. and (
  511. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  512. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  513. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  514. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  515. )
  516. ";
  517. $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  518. set
  519. s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
  520. , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
  521. , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
  522. , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
  523. , s.`A_SYNCHRONIZED`=0
  524. where
  525. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  526. and (
  527. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  528. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  529. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  530. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  531. )
  532. ";
  533. $res = $db->query($sql);
  534. }
  535. public static function generateTasksNewRecords() {
  536. $db = DB::getDB();
  537. if (!$db) die("DB Error: No DB! L." . __LINE__);
  538. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  539. values (-1, '', '', '', '');
  540. ";
  541. $res = $db->query($sql);
  542. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  543. select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
  544. from `IN7_MK_BAZA_DYSTRYBUCJI` as p
  545. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
  546. where p.`A_STATUS`!='DELETED'
  547. ";
  548. $res = $db->query($sql);
  549. }
  550. /**
  551. * Znajdź najstarszy aktualizowany projekt.
  552. */
  553. public static function getTask() {
  554. $task = null;
  555. $db = DB::getDB();
  556. if (!$db) die("DB Error: No DB! L." . __LINE__);
  557. $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
  558. if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0){
  559. $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
  560. }
  561. $sql = "select s.*
  562. , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
  563. , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
  564. , p.`A_CLASSIFIED` as p__A_CLASSIFIED
  565. , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  566. , p.`M_DIST_DESC` as p__M_DIST_DESC
  567. , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
  568. , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
  569. from `_SYNC_FILE_PERMS` as s
  570. left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
  571. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
  572. where
  573. {$sqlWhereProjID}
  574. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  575. limit 1
  576. ";
  577. $res = $db->query($sql);
  578. if ($r = $db->fetch($res)) {
  579. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  580. $task = $r;
  581. }
  582. return $task;
  583. }
  584. public static function getTaskNewerUsers() {
  585. $task = null;
  586. $db = DB::getDB();
  587. if (!$db) die("DB Error: No DB! L." . __LINE__);
  588. $sql = "select s.*
  589. from `_SYNC_FILE_PERMS` as s
  590. where s.`ID_PROJECT`=-2
  591. ";
  592. $res = $db->query($sql);
  593. if ($r = $db->fetch($res)) {
  594. $task = $r;
  595. }
  596. if (!$task) {
  597. $task = new stdClass();
  598. $task->ID_PROJECT = -2;
  599. $task->A_SYNC_RESULT = new stdClass();
  600. $task->A_LAST_SYNC = '';//mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  601. //$task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  602. }
  603. return $task;
  604. }
  605. public static function getTaskNewFiles() {
  606. $task = null;
  607. $db = DB::getDB();
  608. if (!$db) die("DB Error: No DB! L." . __LINE__);
  609. $sql = "select s.*
  610. from `_SYNC_FILE_PERMS` as s
  611. where s.`ID_PROJECT`=-1
  612. ";
  613. $res = $db->query($sql);
  614. if ($r = $db->fetch($res)) {
  615. $task = $r;
  616. }
  617. if (!$task) {
  618. $task = new stdClass();
  619. $task->ID_PROJECT = -1;
  620. $task->A_SYNC_RESULT = new stdClass();
  621. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  622. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  623. }
  624. return $task;
  625. }
  626. public static function saveTask($idProject, $taskDone = 1, $result = null) {
  627. $task = null;
  628. $db = DB::getDB();
  629. if (!$db) die("DB Error: No DB! L." . __LINE__);
  630. $sqlResult = '';
  631. if ($result) {
  632. $resultJson = json_encode($result);
  633. $resultJson = $db->_($resultJson);
  634. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  635. }
  636. $sql = "update `_SYNC_FILE_PERMS` as s
  637. set
  638. s.`A_LAST_SYNC`=NOW()
  639. , s.`A_SYNCHRONIZED`={$taskDone}
  640. {$sqlResult}
  641. where s.`ID_PROJECT`={$idProject}
  642. ";
  643. $res = $db->query($sql);
  644. return $task;
  645. }
  646. public static function executeTask(&$task) {
  647. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  648. $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
  649. $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  650. $project = new stdClass();
  651. $project->ID = $task->ID_PROJECT;
  652. $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
  653. $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
  654. $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
  655. $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
  656. $project->M_DIST_DESC = $task->p__M_DIST_DESC;
  657. $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
  658. $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
  659. $folderConf = FoldersConfig::getAll($confTblName);
  660. $uploader = new FileUploader($confTblName, $project);
  661. $errMsg = '';
  662. if (!$uploader->setConfig($folderConf, $errMsg)) {
  663. trigger_error("Error: folders config!", E_USER_NOTICE);
  664. die("Error: folders config!");
  665. }
  666. $uploader->findFolder();
  667. $mainFolder = $uploader->getDestFolder();
  668. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  669. if (!$mainFolder) {
  670. $mainFolder = $uploader->generateFolderName();
  671. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  672. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  673. mkdir($mainFolderPath, 0770, true);
  674. @chmod($mainFolderPath, 0770);
  675. if (!file_exists($mainFolderPath)) {
  676. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  677. return false;
  678. }
  679. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  680. $file = new stdClass();
  681. $file->name = '.';
  682. $file->path = '.';
  683. //$file->owner = '';
  684. //$file->group = '';
  685. //$file->perms = '';
  686. $file->isDir = true;
  687. $file->permsExt = array();
  688. $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
  689. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  690. }
  691. else {
  692. $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
  693. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProject (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  694. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  695. $folderPismaPath = "{$mainFolderPath}/_PISMA";
  696. // if folder _PISMA not exists then create
  697. $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
  698. $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
  699. if (!empty($cmdKorepList)) {
  700. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProjectKoresp (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdKorepList);echo'</pre>';}
  701. foreach ($cmdKorepList as $vCmd) {
  702. $cmdList[] = $vCmd;
  703. }
  704. }
  705. }
  706. if (!empty($cmdList)) {
  707. foreach ($cmdList as $vCmd) {
  708. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  709. exec($vCmd, $out, $outValue);
  710. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  711. if ($outValue != 0) {
  712. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  713. }
  714. }
  715. }
  716. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  717. }
  718. public static function getActiveLoginList() {
  719. static $activeLoginList;
  720. if (!is_array($activeLoginList)) {
  721. $activeLoginList = array();
  722. $db = DB::getDB();
  723. if (!$db) die("DB Error: No DB! L." . __LINE__);
  724. $sql = "select u.`ADM_ACCOUNT`
  725. from `ADMIN_USERS` as u
  726. where u.`A_STATUS` = 'NORMAL'
  727. ";
  728. $res = $db->query($sql);
  729. while ($r = $db->fetch($res)) {
  730. $activeLoginList[] = $r->ADM_ACCOUNT;
  731. }
  732. }
  733. return $activeLoginList;
  734. }
  735. public static function isActiveUser($login) {
  736. $activeLoginList = self::getActiveLoginList();
  737. return in_array($login, $activeLoginList);
  738. }
  739. public static function getRequiredPermsExtByRecord($project) {
  740. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  741. $requirePermsExt = array();
  742. if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
  743. // TODO: group PODMIOT
  744. $requirePermsExt["group:workgroup"] = array('write', 'read');
  745. }
  746. else {
  747. if ($project->L_APPOITMENT_USER) {
  748. if (self::isActiveUser($project->L_APPOITMENT_USER)) {
  749. $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
  750. } else {
  751. // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
  752. }
  753. }
  754. if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
  755. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
  756. }
  757. else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
  758. $requirePermsExt["group:workgroup"] = array('write', 'read');
  759. }
  760. else {
  761. if ($project->A_ADM_COMPANY) {
  762. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
  763. }
  764. if ($project->A_CLASSIFIED) {
  765. $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
  766. }
  767. }
  768. }
  769. // add parent owner
  770. if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
  771. if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
  772. $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  773. } else {
  774. // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
  775. }
  776. }
  777. // add user:_www perms read, write
  778. $requirePermsExt["user:_www"] = array('write', 'read');
  779. return $requirePermsExt;
  780. }
  781. /**
  782. * Used for files added/modified by samba/afp.
  783. *
  784. * @return TODO: object to store in task->A_SYNC_RESULT
  785. */
  786. public static function fixLastModifiedFiles($task) {
  787. $db = DB::getDB();
  788. if (!$db) die("DB Error: No DB! L." . __LINE__);
  789. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  790. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  791. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  792. $foundProjectFiles = array();
  793. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  794. //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  795. exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  796. if (!empty($filesWithPerms)) {
  797. $filesWithPermsTree = array();
  798. $lastName = '';
  799. foreach ($filesWithPerms as $line) {
  800. if (substr($line, 0, 1) == '-') {// file name
  801. $fileParts = array();
  802. $filePartsArr = explode(' ', $line);
  803. $lastInd = 0;
  804. foreach ($filePartsArr as $vPart) {
  805. if ($lastInd > 7) {// file name
  806. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  807. $lastInd++;
  808. }
  809. else if (!empty($vPart) || $vPart === '0') {
  810. $fileParts[] = $vPart;
  811. $lastInd++;
  812. }
  813. }
  814. $file = new stdClass();
  815. if (!isset($fileParts[8])) {
  816. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  817. //continue;
  818. }
  819. $file->name = end($fileParts);
  820. $file->path = end($fileParts);
  821. //$file->owner = $fileParts[2];
  822. //$file->group = $fileParts[3];
  823. //$file->perms = $fileParts[0];
  824. $file->isDir = (substr($line, 0, 1) == 'd');
  825. $file->permsExt = array();
  826. $filesWithPermsTree[$file->name] = $file;
  827. $lastName = $file->name;
  828. }
  829. else if (substr($line, 0, 1) == ' ') {// extended perm line
  830. if ($lastName == '..') {
  831. continue;
  832. }
  833. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  834. }
  835. else {// parse error
  836. $lastName = '..';
  837. }
  838. }
  839. foreach ($filesWithPermsTree as $vFile) {
  840. $vFile->path = ltrim($vFile->path, './');
  841. $vFile->path = explode('/', $vFile->path);
  842. $vFile->projectFolder = array_shift($vFile->path);
  843. $vFile->path = implode('/', $vFile->path);
  844. $projId = explode('.', $vFile->projectFolder);
  845. $projId = reset($projId);
  846. if (is_numeric($projId) && $projId > 0) {
  847. $foundProjectFiles[$projId][] = $vFile;
  848. }
  849. }
  850. }
  851. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  852. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectFiles);echo'</pre>';}
  853. if (!empty($foundProjectFiles)) {
  854. $sql = "select p.`ID`
  855. , p.`L_APPOITMENT_USER`
  856. , p.`A_ADM_COMPANY`
  857. , p.`A_CLASSIFIED`
  858. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  859. from IN7_MK_BAZA_DYSTRYBUCJI as p
  860. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  861. where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
  862. ";
  863. $res = $db->query($sql);
  864. while ($r = $db->fetch($res)) {
  865. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  866. foreach ($foundProjectFiles[$r->ID] as $vFile) {
  867. $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
  868. if (!empty($cmdList)) {
  869. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  870. foreach ($cmdList as $vCmd) {
  871. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  872. exec($vCmd, $out, $outValue);
  873. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  874. if ($outValue != 0) {
  875. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  876. }
  877. }
  878. } else {
  879. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  880. }
  881. }
  882. }
  883. }
  884. }
  885. public static function fixProjectKoresp($project, $folderPismaPath) {
  886. $db = DB::getDB();
  887. if (!$db) die("DB Error: No DB! L." . __LINE__);
  888. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  889. $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
  890. $pismaList = array();
  891. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  892. $sql = "select k.`ID`
  893. , k.`K_TYP_KORESP`
  894. from `IN7_DZIENNIK_KORESP` as k
  895. where k.`ID_PROJECT`={$project->ID}
  896. order by k.`ID` DESC
  897. limit 100
  898. ";
  899. $res = $db->query($sql);
  900. while ($r = $db->fetch($res)) {
  901. $pismaList[$r->ID] = $r->K_TYP_KORESP;// TODO: K_TYP_KORESP not used
  902. }
  903. if (empty($pismaList)) {
  904. return false;
  905. }
  906. $lsCmd = array();
  907. $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
  908. foreach ($pismaList as $kID => $vTyp) {
  909. $lsCmd[] = "{$kID}.*/";
  910. }
  911. if (empty($lsCmd)) {
  912. return false;
  913. }
  914. $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
  915. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Koreps lsCmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lsCmd);echo'</pre>';}
  916. exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
  917. $filesWithPermsTree = array();
  918. if (!empty($filesWithPerms)) {
  919. $lastName = '';
  920. $folderParent = '';
  921. foreach ($filesWithPerms as $line) {
  922. if (substr($line, 0, 1) == '-') {// file name
  923. $fileParts = array();
  924. $filePartsArr = explode(' ', $line);
  925. $lastInd = 0;
  926. foreach ($filePartsArr as $vPart) {
  927. if ($lastInd > 7) {// file name
  928. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  929. $lastInd++;
  930. }
  931. else if (!empty($vPart) || $vPart === '0') {
  932. $fileParts[] = $vPart;
  933. $lastInd++;
  934. }
  935. }
  936. $file = new stdClass();
  937. if (!isset($fileParts[8])) {
  938. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  939. //continue;
  940. }
  941. $file->name = end($fileParts);
  942. $file->path = array();
  943. if ($folderParent) $file->path[] = $folderParent;
  944. $file->path[] = end($fileParts);
  945. $file->path = implode('/', $file->path);
  946. //$file->owner = $fileParts[2];
  947. //$file->group = $fileParts[3];
  948. //$file->perms = $fileParts[0];
  949. $file->isDir = (substr($line, 0, 1) == 'd');
  950. $file->permsExt = array();
  951. $filesWithPermsTree[$file->name] = $file;
  952. $lastName = $file->name;
  953. }
  954. else if (substr($line, 0, 1) == ' ') {// extended perm line
  955. if ($lastName == '..') {
  956. continue;
  957. }
  958. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  959. }
  960. else if (substr($line, -1) == ':') {// folder
  961. $folderParent = trim(substr($line, 0, -1), '/');
  962. }
  963. else if (substr($line, 0, 5) == 'total') {
  964. continue;
  965. }
  966. else if (empty($line)) {
  967. $folderParent = '';
  968. continue;
  969. }
  970. else {// parse error
  971. $lastName = '..';
  972. }
  973. }
  974. }
  975. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  976. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPermsTree);echo'</pre>';}
  977. $cmdList = array();
  978. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  979. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  980. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
  981. if (!empty($cmdFile)) {
  982. foreach ($cmdFile as $vCmd) {
  983. $cmdList[] = $vCmd;
  984. }
  985. }
  986. // if folder _PISMA not exists then create
  987. $fname = explode('/', $vFile->path);
  988. $fname = end($fname);
  989. $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
  990. }
  991. return $cmdList;
  992. }
  993. /*
  994. * Not used.
  995. */
  996. public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
  997. if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  998. if (isset($task->A_SYNC_RESULT->total)) {
  999. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
  1000. if (!empty($filesTotal)) {
  1001. $filesTotal = reset($filesTotal);
  1002. $filesTotal = intval(trim($filesTotal));
  1003. $task->A_SYNC_RESULT->total = $filesTotal;
  1004. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  1005. }
  1006. }
  1007. }
  1008. }
  1009. public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
  1010. $time = time();
  1011. if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1012. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: pomin - za dużo plików ('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1013. //return false;
  1014. }
  1015. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">r('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1016. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  1017. $filesWithPerms = array();
  1018. $cmd = " ls -Rlea . ";
  1019. if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1020. if (isset($task->A_SYNC_RESULT->total)) {
  1021. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">A_SYNC_RESULT (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("A_SYNC_RESULT[total]={$task->A_SYNC_RESULT->total}");echo'</pre>';}
  1022. if ($task->A_SYNC_RESULT->total > 1000) {
  1023. $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
  1024. if ($lastDone > 0) {
  1025. $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
  1026. $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
  1027. } else {
  1028. $task->A_SYNC_RESULT->lastDone = 1000;
  1029. $cmd = " find . -type f | head -1000 | xargs ls -le ";
  1030. }
  1031. }
  1032. }
  1033. }
  1034. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ");echo'</pre>';}
  1035. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
  1036. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';}
  1037. $filesWithPermsTree = array();
  1038. $lastName = '';
  1039. $folderParent = '';
  1040. foreach ($filesWithPerms as $line) {
  1041. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  1042. $fileParts = array();
  1043. $filePartsArr = explode(' ', $line);
  1044. $lastInd = 0;
  1045. foreach ($filePartsArr as $vPart) {
  1046. if ($lastInd > 7) {// file name
  1047. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1048. $lastInd++;
  1049. }
  1050. else if (!empty($vPart) || $vPart === '0') {
  1051. $fileParts[] = $vPart;
  1052. $lastInd++;
  1053. }
  1054. }
  1055. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  1056. $lastName = '..';
  1057. continue;
  1058. }
  1059. $file = new stdClass();
  1060. if (!isset($fileParts[8])) {
  1061. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1062. //continue;
  1063. }
  1064. $file->name = end($fileParts);
  1065. $file->path = array();
  1066. if ($folderParent) $file->path[] = $folderParent;
  1067. $file->path[] = end($fileParts);
  1068. $file->path = implode('/', $file->path);
  1069. //$file->owner = $fileParts[2];
  1070. //$file->group = $fileParts[3];
  1071. //$file->perms = $fileParts[0];
  1072. $file->isDir = (substr($line, 0, 1) == 'd');
  1073. $file->permsExt = array();
  1074. $filesWithPermsTree[$file->name] = $file;
  1075. $lastName = $file;
  1076. }
  1077. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1078. if ($lastName == '..') {
  1079. continue;
  1080. }
  1081. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1082. }
  1083. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  1084. $folderParent = substr($line, 2, -1);
  1085. }
  1086. else if (substr($line, 0, 5) == 'total') {
  1087. continue;
  1088. }
  1089. else if (empty($line)) {
  1090. $folderParent = '';
  1091. continue;
  1092. }
  1093. }
  1094. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  1095. // check perms
  1096. /*
  1097. files:
  1098. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  1099. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  1100. R read, execute, readattr, readextattr, readsecurity
  1101. dir:
  1102. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  1103. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  1104. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  1105. */
  1106. $cmdList = array();
  1107. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1108. if (false) {
  1109. // TODO: $kFileName == '_PISMA' - readonly
  1110. // TODO: $vFile->path => _PISMA/...
  1111. }
  1112. else {
  1113. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
  1114. if (!empty($cmdFile)) {
  1115. foreach ($cmdFile as $vCmd) {
  1116. $cmdList[] = $vCmd;
  1117. }
  1118. }
  1119. }
  1120. }
  1121. return $cmdList;
  1122. }
  1123. public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1124. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1125. $cmdList = array();
  1126. $vReqPermsExt = array();
  1127. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1128. $vReqPermsExt[$kPermObj] = array();
  1129. foreach ($vPerms as $vPerm) {
  1130. if ($vFile->isDir) {
  1131. if ($vPerm == 'read') {
  1132. $vReqPermsExt[$kPermObj]['list'] = 0;
  1133. $vReqPermsExt[$kPermObj]['search'] = 0;
  1134. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1135. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1136. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1137. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1138. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1139. }
  1140. else if ($vPerm == 'write') {
  1141. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1142. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1143. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1144. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1145. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1146. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1147. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1148. }
  1149. }
  1150. else {
  1151. if ($vPerm == 'read') {
  1152. $vReqPermsExt[$kPermObj]['read'] = 0;
  1153. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1154. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1155. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1156. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1157. }
  1158. else if ($vPerm == 'write') {
  1159. $vReqPermsExt[$kPermObj]['write'] = 0;
  1160. $vReqPermsExt[$kPermObj]['append'] = 0;
  1161. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1162. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1163. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1164. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1165. }
  1166. }
  1167. }
  1168. }
  1169. $permsToRemove = array();
  1170. foreach ($vFile->permsExt as $vPermExtLine) {
  1171. $vPermExtArr = explode(' ', $vPermExtLine);
  1172. $vPermExt = new stdClass();
  1173. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1174. $vPermExt->permObj = $vPermExtArr[1];
  1175. $vPermExt->perms = '';
  1176. if (count($vPermExtArr) == 4) {
  1177. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1178. }
  1179. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1180. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1181. }
  1182. else {
  1183. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1184. continue;
  1185. }
  1186. $permFound = false;
  1187. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1188. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1189. foreach ($vPerms as $kPerm => $vPermChecked) {
  1190. if (in_array($kPerm, $vPermExt->perms)) {
  1191. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1192. $permFound = true;
  1193. }
  1194. }
  1195. }
  1196. }
  1197. if (!$permFound) {
  1198. $permsToRemove[] = $vPermExt->nr;
  1199. }
  1200. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1201. }
  1202. if (!empty($permsToRemove)) {
  1203. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1204. $permsToRemove = array_reverse($permsToRemove);
  1205. foreach ($permsToRemove as $vPermInd) {
  1206. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1207. }
  1208. }
  1209. $permsToAdd = array();
  1210. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1211. foreach ($vPerms as $kPerm => $vPermChecked) {
  1212. if (!$vPermChecked) {
  1213. $permsToAdd[$kPermObj][$kPerm] = 1;
  1214. }
  1215. }
  1216. }
  1217. if (!empty($permsToAdd)) {
  1218. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1219. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1220. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1221. }
  1222. }
  1223. return $cmdList;
  1224. }
  1225. /**
  1226. * @returns array - last modified project ids.
  1227. */
  1228. public static function fixLastModifiedByFiles() {// TODO: RMME
  1229. $db = DB::getDB();
  1230. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1231. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByFiles");echo'</pre>';}
  1232. /*
  1233. * $ man find:
  1234. -newer file
  1235. True if the current file has a more recent last modification time than file.
  1236. -newerXY file
  1237. True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
  1238. or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
  1239. ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
  1240. tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
  1241. *
  1242. * $ man chmod:
  1243. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
  1244. *
  1245. * chmod -a "admin allow write" file1 # remove line
  1246. * chmod -a# 1 file1 # remove line at position 1
  1247. *
  1248. * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
  1249. */
  1250. // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
  1251. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  1252. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  1253. $foundProjectIds = array();
  1254. $lastRunDate = self::getLastRunDate();
  1255. exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
  1256. if (!empty($foundPaths)) {
  1257. foreach ($foundPaths as $path) {
  1258. $path = ltrim($path, './');
  1259. $folder = explode('/', $path);
  1260. $folder = reset($folder);
  1261. $projId = explode('.', $folder);
  1262. $projId = reset($projId);
  1263. if (is_numeric($projId)) {
  1264. $foundProjectIds[$projId] = $folder;
  1265. }
  1266. }
  1267. }
  1268. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundPaths (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundPaths);echo'</pre>';}
  1269. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectIds);echo'</pre>';}
  1270. if (!empty($foundProjectIds)) {
  1271. $sql = "select p.`ID`
  1272. , p.`L_APPOITMENT_USER`
  1273. , p.`A_ADM_COMPANY`
  1274. , p.`A_CLASSIFIED`
  1275. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1276. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1277. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1278. where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
  1279. ";
  1280. $res = $db->query($sql);
  1281. while ($r = $db->fetch($res)) {
  1282. $mainFolder = $foundProjectIds[$r->ID];
  1283. $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
  1284. if (!empty($cmdList)) {
  1285. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1286. } else {
  1287. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1288. }
  1289. }
  1290. }
  1291. return array_keys($foundProjectIds);
  1292. }
  1293. public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
  1294. $db = DB::getDB();
  1295. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1296. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByDB");echo'</pre>';}
  1297. $sqlWhereAdd = '';
  1298. if (!empty($fixedProjIds)) {
  1299. $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
  1300. }
  1301. $projectList = array();
  1302. $lastRunDate = self::getLastRunDate();
  1303. $sql = "select p.`ID`
  1304. , p.`L_APPOITMENT_USER`
  1305. , p.`A_ADM_COMPANY`
  1306. , p.`A_CLASSIFIED`
  1307. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1308. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1309. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1310. where
  1311. ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
  1312. or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
  1313. )
  1314. {$sqlWhereAdd}
  1315. ";
  1316. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1317. $res = $db->query($sql);
  1318. while ($r = $db->fetch($res)) {
  1319. $projectList[$r->ID] = $r;
  1320. }
  1321. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">projectList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($projectList);echo'</pre>';}
  1322. }
  1323. public static function getLastRunDate() {// TODO: RMME
  1324. if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
  1325. // Format: 2013-10-07 23:46
  1326. if (strlen($argFromDate) == 16
  1327. && substr($argFromDate, 4, 1) == '-'
  1328. && substr($argFromDate, 7, 1) == '-'
  1329. && substr($argFromDate, 10, 1) == '-'
  1330. && substr($argFromDate, 13, 1) == ':'
  1331. && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
  1332. ) {
  1333. $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
  1334. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1335. }
  1336. }
  1337. if (!$lastRunDate) {
  1338. $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
  1339. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1340. }
  1341. //$lastRunDate = '2013-09-01 01:00';
  1342. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
  1343. return $lastRunDate;
  1344. }
  1345. public static function usersAction() {
  1346. $task = self::getTaskNewerUsers();
  1347. $users = self::getUsersNewerThen($task->A_LAST_SYNC);
  1348. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1349. self::saveTask(-2);
  1350. }
  1351. public static function usersAllAction() {
  1352. /*
  1353. * DBU - DB User LDU - LDAP User
  1354. * DBG - DB Group LDG - LDAP Group
  1355. *
  1356. * DBU - ADMIN_USERS
  1357. * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
  1358. *
  1359. * 1. fetch DB Users
  1360. * ? only active users (A_STATUS == 'NORMAL')
  1361. * 2. fetch LDAP Users
  1362. *
  1363. * DBU.ADM_ACCOUNT == LDU.uid
  1364. * DBG.A_LDAP_GID == LDG.gidNumber
  1365. *
  1366. * TODO: $group createLdapGroup()
  1367. *
  1368. */
  1369. Lib::loadClass('UsersHelper');
  1370. $users = self::getUsersAll();
  1371. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">users count('.count($users).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1372. $allLdapUsers = UsersHelper::getLDAPUsersAll();
  1373. $ldapUsers = array();
  1374. foreach ($allLdapUsers as $vLdapUser) {
  1375. $ldapUsers[$vLdapUser->uid] = $vLdapUser;
  1376. }
  1377. unset($allLdapUsers);
  1378. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUsers count('.count($ldapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUsers);echo'</pre>';
  1379. foreach ($users as $kLogin => $vUser) {
  1380. if ($vUser->A_STATUS == 'NORMAL') {
  1381. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1382. echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
  1383. }
  1384. else {
  1385. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
  1386. }
  1387. }
  1388. else if ($vUser->A_STATUS == 'DELETED') {
  1389. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1390. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
  1391. }
  1392. else {
  1393. //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
  1394. }
  1395. }
  1396. }
  1397. }
  1398. public static function getUsersNewerThen($datetime) {
  1399. $users = array();
  1400. $db = DB::getDB();
  1401. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1402. $sqlWhereAdd = "";
  1403. if ($datetime) {
  1404. $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
  1405. } else {
  1406. // TODO: error datetime not set
  1407. }
  1408. $sql = "select u.ID
  1409. , u.`ADM_ACCOUNT`
  1410. , u.`ADM_NAME`
  1411. , u.`A_STATUS`
  1412. from `ADMIN_USERS` as u
  1413. where
  1414. u.`A_STATUS` in('NORMAL', 'DELETED')
  1415. ";
  1416. $res = $db->query($sql);
  1417. while ($r = $db->fetch($res)) {
  1418. $users[$r->ADM_ACCOUNT] = $r;
  1419. }
  1420. return $users;
  1421. }
  1422. public static function getUsersAll() {
  1423. $users = array();
  1424. $db = DB::getDB();
  1425. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1426. $sql = "select u.ID
  1427. , u.`ADM_ACCOUNT`
  1428. , u.`ADM_NAME`
  1429. , u.`A_STATUS`
  1430. from `ADMIN_USERS` as u
  1431. where
  1432. u.`A_STATUS` in('NORMAL', 'DELETED')
  1433. ";
  1434. $res = $db->query($sql);
  1435. while ($r = $db->fetch($res)) {
  1436. $users[$r->ADM_ACCOUNT] = $r;
  1437. }
  1438. return $users;
  1439. }
  1440. }
  1441. class SyncPermsCustomTables {
  1442. public $_tbls;
  1443. private $_db;
  1444. private $_syncTblName = '_SYNC_TABLE_FILE_PERMS';
  1445. private $_activeLoginList;
  1446. public function run() {
  1447. if (!$this->fetchConfig()) return;
  1448. $this->installTable();
  1449. $this->generateTasksNewRecords();
  1450. $this->generateTasksUpdated();
  1451. $this->newFilesAction();
  1452. $limit = 100;
  1453. for ($i = 0; $i < $limit; $i++) {
  1454. $loopTasksFired = 0;
  1455. foreach ($this->_tbls as $tblName => $tblConf) {
  1456. $task = $this->nextTaskAction($tblName);
  1457. if (!$task) {
  1458. // TODO: rm $tblName from config to prevent searching for task in next loops
  1459. unset($this->_tbls[$tblName]);
  1460. continue;
  1461. }
  1462. $loopTasksFired++;
  1463. }
  1464. if (!$loopTasksFired) break;
  1465. $i += $loopTasksFired;
  1466. }
  1467. }
  1468. public function fetchConfig() {
  1469. $this->_db = DB::getDB();
  1470. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1471. $tbls = array();
  1472. $sql = "select c.`CONF_VAL` as tbl_names
  1473. from `CRM_CONFIG` as c
  1474. where c.`CONF_KEY`='_SYNC_TABLE_FILE_PERMS__TablesList'
  1475. ";
  1476. $res = $this->_db->query($sql);
  1477. while ($r = $this->_db->fetch($res)) {
  1478. if (!empty($r->tbl_names)) {
  1479. $tbls = explode("\n", $r->tbl_names);
  1480. }
  1481. }
  1482. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', $tbls) . "]\n";
  1483. $configTbls = array();
  1484. Lib::loadClass('FoldersConfig');
  1485. if (!empty($tbls)) {
  1486. $folderConfAll = FoldersConfig::getRawData();
  1487. foreach ($tbls as $tblName) {
  1488. $tblName = trim($tblName);
  1489. if (empty($tblName)) continue;
  1490. $confTblName = "{$tblName}_COLUMN";
  1491. if (FoldersConfig::hasConfig($confTblName)) {
  1492. $configTbls[$tblName] = FoldersConfig::getAll($confTblName);
  1493. }
  1494. }
  1495. }
  1496. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', array_keys($configTbls)) . "]\n";
  1497. if (!empty($configTbls)) {
  1498. $this->_tbls = $configTbls;
  1499. }
  1500. return $this->_tbls;
  1501. }
  1502. public function installTable() {
  1503. if (!$this->_tbls) return;
  1504. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1505. $sql = "
  1506. CREATE TABLE IF NOT EXISTS `{$this->_syncTblName}` (
  1507. `ID` int(11) NOT NULL AUTO_INCREMENT,
  1508. `TBL_NAME` varchar(64),
  1509. `TBL_ID` int(11) NOT NULL,
  1510. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  1511. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  1512. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  1513. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  1514. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  1515. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  1516. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  1517. `A_POMIN_SYNC` tinyint(1) NOT NULL DEFAULT '0',
  1518. PRIMARY KEY (`ID`),
  1519. UNIQUE KEY `TBL` (`TBL_NAME`, `TBL_ID`)
  1520. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  1521. ";
  1522. $this->_db->query($sql);
  1523. if ($this->_db->has_errors()) {
  1524. print_r($this->_db->get_errors());
  1525. }
  1526. }
  1527. public function generateTasksNewRecords() {
  1528. if (!$this->_tbls) return;
  1529. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1530. $sqlValues = array();
  1531. foreach ($this->_tbls as $tblName => $tblConf) {
  1532. $sqlValues[] = "('{$tblName}', -1, '', '', '', '')";
  1533. }
  1534. $sqlValues = implode(',', $sqlValues);
  1535. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1536. values {$sqlValues};
  1537. ";
  1538. $res = $this->_db->query($sql);
  1539. if ($this->_db->has_errors()) {
  1540. print_r($this->_db->get_errors());
  1541. }
  1542. foreach ($this->_tbls as $tblName => $tblConf) {
  1543. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1544. select '{$tblName}' as TBL_NAME
  1545. , t.`ID`, t.`L_APPOITMENT_USER`, t.`A_ADM_COMPANY`, t.`A_CLASSIFIED`
  1546. , '' as PARENT_L_APPOITMENT_USER -- pp.`L_APPOITMENT_USER`
  1547. from `{$tblName}` as t
  1548. where t.`A_STATUS`!='DELETED'
  1549. ";
  1550. $res = $this->_db->query($sql);
  1551. if ($this->_db->has_errors()) {
  1552. print_r($this->_db->get_errors());
  1553. }
  1554. }
  1555. }
  1556. public function generateTasksUpdated() {
  1557. if (!$this->_tbls) return;
  1558. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1559. foreach ($this->_tbls as $tblName => $tblConf) {
  1560. $sql = "update `{$this->_syncTblName}` as s
  1561. , `{$tblName}` as t
  1562. -- , `IN7_MK_BAZA_DYSTRYBUCJI` as pt
  1563. set
  1564. s.`L_APPOITMENT_USER`=t.`L_APPOITMENT_USER`
  1565. , s.`A_ADM_COMPANY`=t.`A_ADM_COMPANY`
  1566. , s.`A_CLASSIFIED`=t.`A_CLASSIFIED`
  1567. , s.`PARENT_L_APPOITMENT_USER`='' -- pt.`L_APPOITMENT_USER`
  1568. , s.`A_SYNCHRONIZED`=0
  1569. where
  1570. s.`TBL_ID`=t.`ID`
  1571. and s.`TBL_NAME`='{$tblName}'
  1572. -- and pt.`ID`=t.`P_ID`
  1573. and (
  1574. s.`L_APPOITMENT_USER`!=t.`L_APPOITMENT_USER`
  1575. or s.`A_ADM_COMPANY`!=t.`A_ADM_COMPANY`
  1576. or s.`A_CLASSIFIED`!=t.`A_CLASSIFIED`
  1577. -- or s.`PARENT_L_APPOITMENT_USER`!=pt.`L_APPOITMENT_USER`
  1578. )
  1579. ";
  1580. $res = $this->_db->query($sql);
  1581. if ($this->_db->has_errors()) {
  1582. print_r($this->_db->get_errors());
  1583. }
  1584. }
  1585. }
  1586. public function newFilesAction() {
  1587. if (!$this->_tbls) return;
  1588. foreach ($this->_tbls as $tblName => $tblConf) {
  1589. $task = $this->_getTaskNewFiles($tblName);
  1590. $taskResult = $this->_fixLastModifiedFiles($task);
  1591. $this->_saveTask($tblName, -1);
  1592. }
  1593. }
  1594. private function _getTaskNewFiles($tblName) {
  1595. $task = null;
  1596. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1597. $sql = "select s.*
  1598. from `{$this->_syncTblName}` as s
  1599. where s.`TBL_ID`=-1 and s.`TBL_NAME`='{$tblName}'
  1600. ";
  1601. $res = $this->_db->query($sql);
  1602. if ($r = $this->_db->fetch($res)) {
  1603. $task = $r;
  1604. }
  1605. if (!$task) {
  1606. $task = new stdClass();
  1607. $task->TBL_NAME = $tblName;
  1608. $task->TBL_ID = -1;
  1609. $task->A_SYNC_RESULT = new stdClass();
  1610. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  1611. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  1612. }
  1613. return $task;
  1614. }
  1615. private function _fixLastModifiedFiles($task) {
  1616. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1617. $tblName = $task->TBL_NAME;
  1618. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  1619. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1620. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1621. $record = null;
  1622. $folderConf = FoldersConfig::getAll($confTblName);
  1623. $uploader = new FileUploader($confTblName, $record);
  1624. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1625. trigger_error("Error: folders config!", E_USER_NOTICE);
  1626. die("Error: folders config!");
  1627. }
  1628. $hasRecordOwnFolder = $uploader->hasRecordOwnFolder();
  1629. $foundTblFiles = array();
  1630. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  1631. //exec("cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  1632. $filesWithPerms = array();
  1633. $cmd = "cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;";
  1634. exec($cmd, $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  1635. if (!empty($filesWithPerms)) {
  1636. $filesWithPermsTree = array();
  1637. $lastName = '';
  1638. foreach ($filesWithPerms as $line) {
  1639. if (substr($line, 0, 1) == '-') {// file name
  1640. $fileParts = array();
  1641. $filePartsArr = explode(' ', $line);
  1642. $lastInd = 0;
  1643. foreach ($filePartsArr as $vPart) {
  1644. if ($lastInd > 7) {// file name
  1645. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1646. $lastInd++;
  1647. }
  1648. else if (!empty($vPart) || $vPart === '0') {
  1649. $fileParts[] = $vPart;
  1650. $lastInd++;
  1651. }
  1652. }
  1653. $file = new stdClass();
  1654. if (!isset($fileParts[8])) {
  1655. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1656. //continue;
  1657. }
  1658. $file->name = end($fileParts);
  1659. $file->path = end($fileParts);
  1660. //$file->owner = $fileParts[2];
  1661. //$file->group = $fileParts[3];
  1662. //$file->perms = $fileParts[0];
  1663. $file->isDir = (substr($line, 0, 1) == 'd');
  1664. $file->permsExt = array();
  1665. $filesWithPermsTree[$file->name] = $file;
  1666. $lastName = $file->name;
  1667. }
  1668. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1669. if ($lastName == '..') {
  1670. continue;
  1671. }
  1672. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1673. }
  1674. else {// parse error
  1675. $lastName = '..';
  1676. }
  1677. }
  1678. foreach ($filesWithPermsTree as $vFile) {
  1679. $vFile->path = ltrim($vFile->path, './');
  1680. $vFile->path = explode('/', $vFile->path);
  1681. $vFile->recordFolder = array_shift($vFile->path);// $vFile->projectFolder -> recordFolder
  1682. $vFile->path = implode('/', $vFile->path);
  1683. // TODO: _getTableIdFromFolderName($task->TBL_NAME, $vFile->recordFolder);
  1684. $tblId = 0;
  1685. if ($hasRecordOwnFolder) {
  1686. $tblId = explode('.', $vFile->recordFolder);
  1687. $tblId = reset($tblId);
  1688. }
  1689. else {
  1690. $tblId = explode('.', $vFile->path);
  1691. $tblId = reset($tblId);
  1692. }
  1693. if (is_numeric($tblId) && $tblId > 0) {
  1694. $foundTblFiles[$tblId][] = $vFile;
  1695. }
  1696. }
  1697. }
  1698. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  1699. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundTblFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($foundTblFiles);echo'</pre>';}
  1700. if (!empty($foundTblFiles)) {
  1701. $rowsIds = array_keys($foundTblFiles);
  1702. $sql = "select t.`ID`
  1703. , t.`L_APPOITMENT_USER`
  1704. , t.`A_ADM_COMPANY`
  1705. , t.`A_CLASSIFIED`
  1706. -- , pt.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1707. from `{$task->TBL_NAME}` as t
  1708. -- left join `{$task->TBL_NAME}` as pt on (pt.ID=t.P_ID)
  1709. where t.`ID` in (" . implode(',', $rowsIds) . ")
  1710. ";
  1711. $res = $this->_db->query($sql);
  1712. while ($r = $this->_db->fetch($res)) {
  1713. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  1714. foreach ($foundTblFiles[$r->ID] as $vFile) {
  1715. $cmdList = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$vFile->recordFolder}", $r);
  1716. if (!empty($cmdList)) {
  1717. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1718. foreach ($cmdList as $vCmd) {
  1719. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  1720. exec($vCmd, $out, $outValue);
  1721. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  1722. if ($outValue != 0) {
  1723. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  1724. }
  1725. }
  1726. } else {
  1727. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  1728. }
  1729. }
  1730. }
  1731. }
  1732. }
  1733. public function _getRequiredPermsExtByRecord($record) {
  1734. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  1735. $requirePermsExt = array();
  1736. if (!$record->L_APPOITMENT_USER && !$record->A_ADM_COMPANY) {// no owner, no write group
  1737. // TODO: group PODMIOT
  1738. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1739. }
  1740. else {
  1741. if ($record->L_APPOITMENT_USER) {
  1742. if ($this->_isActiveUser($record->L_APPOITMENT_USER)) {
  1743. $requirePermsExt["user:{$record->L_APPOITMENT_USER}"] = array('write', 'read');
  1744. } else {
  1745. // TODO: trigger error $record->L_APPOITMENT_USER is not active user!
  1746. }
  1747. }
  1748. if (!empty($record->A_ADM_COMPANY) && $record->A_ADM_COMPANY == $record->A_CLASSIFIED) {
  1749. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('read', 'write');
  1750. }
  1751. else if (empty($record->A_ADM_COMPANY) && empty($record->A_CLASSIFIED)) {
  1752. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1753. }
  1754. else {
  1755. if ($record->A_ADM_COMPANY) {
  1756. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('write');
  1757. }
  1758. if ($record->A_CLASSIFIED) {
  1759. $requirePermsExt["group:{$record->A_CLASSIFIED}"] = array('read');
  1760. }
  1761. }
  1762. }
  1763. // add parent owner
  1764. if (!empty($record->PARENT_L_APPOITMENT_USER) && $record->PARENT_L_APPOITMENT_USER != $record->L_APPOITMENT_USER) {
  1765. if ($this->_isActiveUser($record->PARENT_L_APPOITMENT_USER)) {
  1766. $requirePermsExt["user:{$record->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  1767. } else {
  1768. // TODO: trigger error $record->PARENT_L_APPOITMENT_USER is not active user!
  1769. }
  1770. }
  1771. // add user:_www perms read, write
  1772. $requirePermsExt["user:_www"] = array('write', 'read');
  1773. return $requirePermsExt;
  1774. }
  1775. private function _fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1776. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1777. $cmdList = array();
  1778. $vReqPermsExt = array();
  1779. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1780. $vReqPermsExt[$kPermObj] = array();
  1781. foreach ($vPerms as $vPerm) {
  1782. if ($vFile->isDir) {
  1783. if ($vPerm == 'read') {
  1784. $vReqPermsExt[$kPermObj]['list'] = 0;
  1785. $vReqPermsExt[$kPermObj]['search'] = 0;
  1786. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1787. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1788. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1789. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1790. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1791. }
  1792. else if ($vPerm == 'write') {
  1793. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1794. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1795. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1796. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1797. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1798. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1799. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1800. }
  1801. }
  1802. else {
  1803. if ($vPerm == 'read') {
  1804. $vReqPermsExt[$kPermObj]['read'] = 0;
  1805. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1806. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1807. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1808. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1809. }
  1810. else if ($vPerm == 'write') {
  1811. $vReqPermsExt[$kPermObj]['write'] = 0;
  1812. $vReqPermsExt[$kPermObj]['append'] = 0;
  1813. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1814. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1815. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1816. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1817. }
  1818. }
  1819. }
  1820. }
  1821. $permsToRemove = array();
  1822. foreach ($vFile->permsExt as $vPermExtLine) {
  1823. $vPermExtArr = explode(' ', $vPermExtLine);
  1824. $vPermExt = new stdClass();
  1825. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1826. $vPermExt->permObj = $vPermExtArr[1];
  1827. $vPermExt->perms = '';
  1828. if (count($vPermExtArr) == 4) {
  1829. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1830. }
  1831. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1832. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1833. }
  1834. else {
  1835. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1836. continue;
  1837. }
  1838. $permFound = false;
  1839. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1840. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1841. foreach ($vPerms as $kPerm => $vPermChecked) {
  1842. if (in_array($kPerm, $vPermExt->perms)) {
  1843. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1844. $permFound = true;
  1845. }
  1846. }
  1847. }
  1848. }
  1849. if (!$permFound) {
  1850. $permsToRemove[] = $vPermExt->nr;
  1851. }
  1852. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1853. }
  1854. if (!empty($permsToRemove)) {
  1855. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1856. $permsToRemove = array_reverse($permsToRemove);
  1857. foreach ($permsToRemove as $vPermInd) {
  1858. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1859. }
  1860. }
  1861. $permsToAdd = array();
  1862. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1863. foreach ($vPerms as $kPerm => $vPermChecked) {
  1864. if (!$vPermChecked) {
  1865. $permsToAdd[$kPermObj][$kPerm] = 1;
  1866. }
  1867. }
  1868. }
  1869. if (!empty($permsToAdd)) {
  1870. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1871. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1872. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1873. }
  1874. }
  1875. return $cmdList;
  1876. }
  1877. private function _isActiveUser($usrLogin) {
  1878. $activeLoginList = $this->_fetchActiveLoginList();
  1879. return in_array($usrLogin, $activeLoginList);
  1880. }
  1881. public function _fetchActiveLoginList() {
  1882. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1883. if (!is_array($this->_activeLoginList)) {
  1884. $this->_activeLoginList = array();
  1885. $sql = "select u.`ADM_ACCOUNT`
  1886. from `ADMIN_USERS` as u
  1887. where u.`A_STATUS` = 'NORMAL'
  1888. ";
  1889. $res = $this->_db->query($sql);
  1890. while ($r = $this->_db->fetch($res)) {
  1891. $this->_activeLoginList[] = $r->ADM_ACCOUNT;
  1892. }
  1893. }
  1894. return $this->_activeLoginList;
  1895. }
  1896. private function _saveTask($tblName, $tblId, $taskDone = 1, $result = null) {
  1897. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1898. $sqlResult = '';
  1899. if ($result) {
  1900. $resultJson = json_encode($result);
  1901. $resultJson = $this->_db->_($resultJson);
  1902. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  1903. }
  1904. $sql = "update `{$this->_syncTblName}` as s
  1905. set
  1906. s.`A_LAST_SYNC`=NOW()
  1907. , s.`A_SYNCHRONIZED`={$taskDone}
  1908. {$sqlResult}
  1909. where s.`TBL_ID`={$tblId} and s.`TBL_NAME`='{$tblName}'
  1910. ";
  1911. $res = $this->_db->query($sql);
  1912. }
  1913. public function executeTask($tblName, $tblId) {
  1914. if (!$this->_tbls) return;
  1915. $task = $this->_getTask($tblName, $tblId);
  1916. if (!$task) return;
  1917. $this->_executeTask($task);
  1918. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1919. return $task;
  1920. }
  1921. public function nextTaskAction($tblName) {
  1922. if (!$this->_tbls) return;
  1923. $task = $this->_getTask($tblName);
  1924. if (!$task) return;
  1925. $this->_executeTask($task);
  1926. /*
  1927. if (isset($task->A_SYNC_RESULT->total)
  1928. && isset($task->A_SYNC_RESULT->lastDone)
  1929. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  1930. ) {
  1931. $this->_saveTask($task->TBL_NAME, $task->TBL_ID, 0, $task->A_SYNC_RESULT);
  1932. } else {
  1933. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1934. }
  1935. */
  1936. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1937. return $task;
  1938. }
  1939. private function _getTask($tblName, $tblId = null) {
  1940. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1941. $task = null;
  1942. $recordFieldList = $this->_getRecordFieldList($tblName);
  1943. $recordFieldList[] = 'L_APPOITMENT_USER';
  1944. $recordFieldList[] = 'A_ADM_COMPANY';
  1945. $recordFieldList[] = 'A_CLASSIFIED';
  1946. $sqlRecordFields = array();
  1947. foreach ($recordFieldList as $fldName) {
  1948. $sqlRecordFields[] = "t.`{$fldName}` as t__{$fldName}";
  1949. }
  1950. $sqlRecordFields = implode(',', $sqlRecordFields);
  1951. $sqlTblId = "and s.`TBL_ID`!=-1";
  1952. if ($tblId > 0) $sqlTblId = "and s.`TBL_ID`='{$tblId}'";
  1953. $sql = "select s.*
  1954. , {$sqlRecordFields}
  1955. -- , pt.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  1956. from `{$this->_syncTblName}` as s
  1957. left join `{$tblName}` as t on(t.`ID`=s.`TBL_ID`)
  1958. -- left join `{$tblName}` as pt on(pt.`ID`=t.`P_ID`)
  1959. where
  1960. s.`TBL_NAME`='{$tblName}'
  1961. {$sqlTblId}
  1962. and s.`A_SYNCHRONIZED`=0
  1963. and s.`A_POMIN_SYNC`=0
  1964. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  1965. limit 1
  1966. ";
  1967. $res = $this->_db->query($sql);
  1968. if ($r = $this->_db->fetch($res)) {
  1969. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  1970. $task = $r;
  1971. $task->record = new stdClass();
  1972. foreach ($recordFieldList as $fldName) {
  1973. $aliasFldName = "t__{$fldName}";
  1974. $task->record->{$fldName} = $task->{$aliasFldName};
  1975. unset($task->{$aliasFldName});
  1976. }
  1977. }
  1978. return $task;
  1979. }
  1980. private function _getRecordFieldList($tblName) {
  1981. if (empty($this->_tbls[$tblName])) return;
  1982. $conf = $this->_tbls[$tblName];
  1983. $fldNames = array();
  1984. $fldName = V::get("LOOKAT_FOLDER_VARNAME", '', $conf);
  1985. $fldName = trim($fldName);
  1986. if (!empty($fldName)) $fldNames[$fldName] = true;
  1987. for ($i = 1; $i < 5; $i++) {
  1988. $fldName = V::get("LOOKAT_FOLDER_VARNAME{$i}", '', $conf);
  1989. $fldName = trim($fldName);
  1990. if (!empty($fldName)) $fldNames[$fldName] = true;
  1991. $fldName = V::get("DEST_FOLDER_VARNAME{$i}", '', $conf);
  1992. $fldName = trim($fldName);
  1993. if (!empty($fldName)) $fldNames[$fldName] = true;
  1994. }
  1995. if (!in_array('ID', $fldNames)) {
  1996. $fldNames['ID'] = true;
  1997. }
  1998. return array_keys($fldNames);
  1999. }
  2000. private function _executeTask($task) {
  2001. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  2002. $DBG_TIME = false;
  2003. $dbgTime = new stdClass();
  2004. $dbgTime->startTime = microtime(true);
  2005. $dbgTime->lastTime = $dbgTime->startTime;
  2006. $confTblName = "{$task->TBL_NAME}_COLUMN";
  2007. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  2008. $record = $task->record;
  2009. $folderConf = FoldersConfig::getAll($confTblName);
  2010. $uploader = new FileUploader($confTblName, $record);
  2011. $errMsg = '';
  2012. if (!$uploader->setConfig($folderConf, $errMsg)) {
  2013. trigger_error("Error: folders config!", E_USER_NOTICE);
  2014. die("Error: folders config!");
  2015. }
  2016. if ($DBG_TIME) {
  2017. $dbgTime->curTime = microtime(true);
  2018. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-FileUploader->setConfig" . "\n";
  2019. $dbgTime->lastTime = $dbgTime->curTime;
  2020. }
  2021. $uploader->findFolder();
  2022. $mainFolder = $uploader->getDestFolder();
  2023. if ($DBG_TIME) {
  2024. $dbgTime->curTime = microtime(true);
  2025. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]:time after-FileUploader->getDestFolder" . "\n";
  2026. $dbgTime->lastTime = $dbgTime->curTime;
  2027. }
  2028. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  2029. if (!$mainFolder) {
  2030. $mainFolder = $uploader->generateFolderName();
  2031. $mainFolderPath = rtrim($TBL_mount_point, '/') . '/' . $mainFolder;
  2032. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  2033. @mkdir($mainFolderPath, 0770, true);
  2034. @chmod($mainFolderPath, 0770);
  2035. if (!file_exists($mainFolderPath)) {
  2036. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  2037. return false;
  2038. }
  2039. $requirePermsExt = $this->_getRequiredPermsExtByRecord($record);
  2040. $file = new stdClass();
  2041. $file->name = '.';
  2042. $file->path = '.';
  2043. //$file->owner = '';
  2044. //$file->group = '';
  2045. //$file->perms = '';
  2046. $file->isDir = true;
  2047. $file->permsExt = array();
  2048. $cmdList = $this->_fixFilePerms($file, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $record);
  2049. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$record->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  2050. }
  2051. else {
  2052. $cmdList = $this->_fixRecord($record, $uploader, $mainFolder, $TBL_mount_point, $task);
  2053. }
  2054. if ($DBG_TIME) {
  2055. $dbgTime->curTime = microtime(true);
  2056. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-generate cmdList - mainFolder(" . (($mainFolder)? 1 : 0) . ")" . "\n";
  2057. $dbgTime->lastTime = $dbgTime->curTime;
  2058. }
  2059. if (!empty($cmdList)) {
  2060. foreach ($cmdList as $vCmd) {
  2061. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  2062. exec($vCmd, $out, $outValue);
  2063. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  2064. if ($outValue != 0) {
  2065. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  2066. }
  2067. }
  2068. }
  2069. if ($DBG_TIME) {
  2070. $dbgTime->curTime = microtime(true);
  2071. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-executed cmdList " . "\n";
  2072. $dbgTime->lastTime = $dbgTime->curTime;
  2073. }
  2074. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  2075. }
  2076. public function _fixRecord($r, $uploader, $mainFolder, $TBL_mount_point, &$task) {
  2077. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  2078. $DBG_TIME = false;
  2079. $dbgTime = new stdClass();
  2080. $dbgTime->startTime = microtime(true);
  2081. $dbgTime->lastTime = $dbgTime->startTime;
  2082. $filesWithPerms = array();
  2083. if ($uploader->hasRecordOwnFolder()) {
  2084. $cmd = " ls -Rlea . ";
  2085. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2086. exec($cmd, $filesWithPerms);
  2087. }
  2088. else {
  2089. $lookGlob = $uploader->getFileSearchRegex();
  2090. $cmd = " ls -Rlea {$lookGlob} ";
  2091. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2092. exec($cmd, $filesWithPerms);
  2093. }
  2094. //echo "\n-----------------------\n";
  2095. //echo "filesWithPerms: ";print_r($filesWithPerms);echo "\n";
  2096. if ($DBG_TIME) {
  2097. $dbgTime->curTime = microtime(true);
  2098. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} " . "\n";
  2099. $dbgTime->lastTime = $dbgTime->curTime;
  2100. }
  2101. $filesWithPermsTree = array();
  2102. $lastName = '';
  2103. $folderParent = '';
  2104. foreach ($filesWithPerms as $line) {
  2105. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  2106. $fileParts = array();
  2107. $filePartsArr = explode(' ', $line);
  2108. $lastInd = 0;
  2109. foreach ($filePartsArr as $vPart) {
  2110. if ($lastInd > 7) {// file name
  2111. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  2112. $lastInd++;
  2113. }
  2114. else if (!empty($vPart) || $vPart === '0') {
  2115. $fileParts[] = $vPart;
  2116. $lastInd++;
  2117. }
  2118. }
  2119. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  2120. $lastName = '..';
  2121. continue;
  2122. }
  2123. $file = new stdClass();
  2124. if (!isset($fileParts[8])) {
  2125. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  2126. //continue;
  2127. }
  2128. $file->name = end($fileParts);
  2129. $file->path = array();
  2130. if ($folderParent) $file->path[] = $folderParent;
  2131. $file->path[] = end($fileParts);
  2132. $file->path = implode('/', $file->path);
  2133. //$file->owner = $fileParts[2];
  2134. //$file->group = $fileParts[3];
  2135. //$file->perms = $fileParts[0];
  2136. $file->isDir = (substr($line, 0, 1) == 'd');
  2137. $file->permsExt = array();
  2138. $filesWithPermsTree[$file->name] = $file;
  2139. $lastName = $file;
  2140. }
  2141. else if (substr($line, 0, 1) == ' ') {// extended perm line
  2142. if ($lastName == '..') {
  2143. continue;
  2144. }
  2145. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  2146. }
  2147. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  2148. $folderParent = substr($line, 2, -1);
  2149. }
  2150. else if (substr($line, 0, 5) == 'total') {
  2151. continue;
  2152. }
  2153. else if (empty($line)) {
  2154. $folderParent = '';
  2155. continue;
  2156. }
  2157. }
  2158. //echo "filesWithPermsTree: ";print_r($filesWithPermsTree);echo "\n";
  2159. if ($DBG_TIME) {
  2160. $dbgTime->curTime = microtime(true);
  2161. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: parse cmd output" . "\n";
  2162. $dbgTime->lastTime = $dbgTime->curTime;
  2163. }
  2164. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  2165. // check perms
  2166. /*
  2167. files:
  2168. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  2169. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  2170. R read, execute, readattr, readextattr, readsecurity
  2171. dir:
  2172. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  2173. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  2174. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  2175. */
  2176. $cmdList = array();
  2177. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  2178. if (false) {
  2179. // TODO: $kFileName == '_PISMA' - readonly
  2180. // TODO: $vFile->path => _PISMA/...
  2181. }
  2182. else {
  2183. $cmdFile = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $r);
  2184. if (!empty($cmdFile)) {
  2185. foreach ($cmdFile as $vCmd) {
  2186. $cmdList[] = $vCmd;
  2187. }
  2188. }
  2189. }
  2190. }
  2191. //echo "cmdList: ";print_r($cmdList);echo "\n";
  2192. //echo "\n-----------------------\n";
  2193. if ($DBG_TIME) {
  2194. $dbgTime->curTime = microtime(true);
  2195. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: end" . "\n";
  2196. $dbgTime->lastTime = $dbgTime->curTime;
  2197. }
  2198. return $cmdList;
  2199. }
  2200. }
  2201. ?>